Check if Form Input is Valid With JavaScript - javascript

I am currently trying to make a login / create account page for a website that I am developing for fun. In the create account form, I have an input field for username, name, email, password, and verify password. I also have patterns in the input fields so that the user makes valid account info. Here is the form below:
<form method="post" action="CreateAccount.php">
<h1>Create Account</h1>
<input class="inputInfo" type="text" name="username" id="newUsername" pattern="[A-Za-z0-9]+" placeholder="Username" maxlength="40" minlength="5" onkeyup="checkInput()" onblur="checkInput()" autocomplete="off" required/>
<input class="inputInfo" type="text" name="fullname" id="newName" placeholder="First and Last Name" onkeyup="checkInput()" onblur="checkInput()" minlength="3" autocomplete="off" required/>
<input class="inputInfo" type="email" name="email" id="newEmail" pattern="[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,}$" title="Must be a real email" placeholder="Email" onkeyup="checkInput()" onblur="checkInput()" required/>
<input class="inputInfo" type="password" name="password" id="newPassword" pattern="(?=^.{8,}$)((?=.*\d)|(?=.*\W+))(?![.\n])(?=.*[A-Z])(?=.*[a-z]).*$" placeholder="Password"
title="Must be 8 or more characters with at least one number or special character, uppercase letter, and lowercase letter" onkeypress="checkInput()" onblur="checkInput()" required/>
<input class="inputInfo" type="password" name="verifypassword" id="verifyPass" pattern="(?=^.{8,}$)((?=.*\d)|(?=.*\W+))(?![.\n])(?=.*[A-Z])(?=.*[a-z]).*$" placeholder="Verify Password"
title="Must be 8 or more characters with at least one number or special character, uppercase letter, and lowercase letter" onkeypress="checkInput()" onblur="checkInput()" required/>
<span><label for="showp"><input type="checkbox" id="showp" onclick="showPassword()">Show Password</label></span>
<button type="submit" style="margin-top: 7px;" class="disabled" id="submitButton">Sign Up</button>
<p style="font-size: 10px;">By signing up, you agree to our Terms , Data Policy and Cookies Policy .</p>
</form>
For clarification: the username pattern requires you to have a username with only upper and lower case letters and numbers and must be at least 5 characters and at most 40 characters. The email requires you to input a valid email address pattern. And the password requires a password that is at least 8 characters and must have an uppercase and lowercase letter and a number or special character.
In the input fields, you will see that I have a function called during blur or keyup event that is called checkInput(). The purpose of the function is to ensure that the input fields have the necessary length before the submit button can be enabled:
function checkInput ()
{
let usernameLength = document.getElementById('newUsername').value.length;
let nameLength = document.getElementById('newName').value.length;
let emailLength = document.getElementById('newEmail').value.length;
let passwordLength = document.getElementById('newPassword').value.length;
let verifyLength = document.getElementById('verifyPass').value.length;
if (usernameLength >= 5 && nameLength > 0 && emailLength > 0 && passwordLength >= 8 && verifyLength >= 8)
{
document.getElementById('submitButton').disabled = false;
const element = document.querySelector('#submitButton');
if (element.classList.contains('disabled'))
{
element.classList.remove('disabled');
}
}
else
{
document.getElementById('submitButton').disabled = true;
const addElement = document.querySelector('#submitButton');
addElement.classList.add('disabled');
}
}
I also have the following CSS classes that either make the border and shadow of the input field green or red:
.validInput {
border-color: #50c878;
box-shadow: 0 0 5px #50c878;
}
.invalidInput {
border-color: #ff0000;
box-shadow: 0 0 5px #ff0000;
}
My problem is that I would like to add some javascript so that while the user is typing in their information into the form, the code checks to make sure their input matches the patterns that are stated in the input fields. If the input they are putting into the field is valid, I would like for the javascript to add the validInput class to the input field. If the input is invalid I would like to add the invalidInput class to the input field. I have no idea, though, how to go about having JavaScript check if the input follows the pattern.
I would also like to make it to where it checks if the input is valid every time the user has a change event.
Does anyone have any ideas on how to go about doing this?

You can use the addEventListener function with 'change' parameter if you want your verification to run after the user leaves the field, or with 'input' parameter if you want the verification to run each time the user writes something in the text field. This should do it for you:
// If you want the verification to run when the user leaves the input.
document.getElementById('newUsername').addEventListener("change", checkInput);
// If you want the verification to run each time the user changes the input.
document.getElementById('newUsername').addEventListener("input", checkInput);
For the verification part, you can use regex. Create the verification functions first, (checks if the input is valid):
let check_username = (username)=>{
let rx = /^[a-z0-9]{8,40}$/i;
return rx.test(username); // Checks if the username is only made of alphanumeric characters (case insentisive)
}
let check_password = (password)=>{
let special_char = /[0-9!##\$%\^\&*\)\(+=._-]/; // If you want more special characters add them inside the braces at the end (after the '=+._-')
let upper_char = /[a-z]/;
let lower_char = /[A-Z]/;
return special_char.test(password) // Checks if the password contains a special character or a number
&& upper_char.test(password) // Checks if the password contains an upper case letter
&& lower_char.test(password) // Checks if the password contains a lower case letter
&& password.length>=8; // checks the password length
}
let check_email = (email)=>{
let rx = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+#[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)+$/;
return rx.test(email); // Checks the mail format.
}
Then you can use them like that:
check_username(document.getElementById('newUsername').value)
// This should return true if the username is valid or false if not.
Hope this was helpful. You can close the subject if that's what you are looking for.

Related

The input from client side should entered only digits, if is alphabets should give an error msg

Create an html page with the following form:
<form method="post" name="example" action="">
<p> Enter your name <input type="text"> </p>
<input type="submit" value="Submit Information" />
</form>
<div id="a"></div>
Add a js validation function to the form that ensures that you can only add numbers in the textbox If you enter alphabets, you should generate an error message in the given div. -->
I run the requirement successfully and I'm giving the error message when it entered alphabets. However, it's giving me the same error message when I enter digits as well. Please kindly show how the function or the window.onload should be implemented. Thank you.
My answer is down below;
window.onload = function() {
let form = document.getElementById('form_ref')
form.onsubmit = function() {
let user = form.user.value;
if (parseInt(user) !== user) {
document.querySelector('div').innerHTML = "Error! Please enter digits only!";
return false;
}
return true;
}
}
<form id="form_ref" method="post" name="example" action="">
<label for="username">User</label><input type="text" name="user" id="username" required>
<div id="a"></div>
<br>
<input type="submit" value="Submit Information" id="submit">
</form>
Your equality check parseInt(user) !== user will always return true because form.user.value is a string but parseInt(...) always returns an integer. If you want to check if the entry is an integer there are a couple ways.
You can change the input's type attribute to number to make sure only digits can be entered and then you just have to make sure it's an integer and not a decimal (type="number" still allows decimal numbers so not just digits). user will still be a string, but it's easier to check. I'd recommend using Number.isInteger(...) to do the checking:
if (!Number.isInteger(parseFloat(user))) {
If you really want to use type="text" you can iterate through user and make sure its characters are all digits:
for(let i = 0; i < user.length; i++) {
if("0123456789".indexOf(user[i]) == -1) {
document.querySelector('div').innerHTML = "Error! Please enter digits only!";
return false;
}
}
return true;
One advantage of this method is that you can make more characters available if you want to just by adding them to the string that's searched in the iteration. A disadvantage is that it's slower than the other method (the indexOf method has to iterate through the string for every character of user), but for your use case that seems irrelevant-- this function doesn't need to be called many times per second as it's a simple login type of thing, and it's client-side so you don't need to handle many instances at once. If speed is an issue you could probably make a comparison to the integer equivalencies of the characters:
if(user.charCodeAt(i) < "0".charCodeAt(0) || user.charCodeAt(i) > "9".charCodeAt(0)) {

Set focus to another field in web form with javascript

I have a web form with two fields:
Email
User name
I want to track user input in the Email field and when it ends with ".com" set focus to another field "User email"
What the best way to do so with JavaScript or jQuery.
This should do the trick. When the last 4 letters of the email input are '.com', the focus is given to the username field.
While this works, please consider the UX issues this may cause. In the comments for your question, Quentin provides a good explanation of why this probably isn't worth implementing.
$('#email').on('input', function() {
email = this.value
if (email.substr(email.length - 4) === '.com')
$('#username').focus()
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="email" type="text" placeholder="email">
<input id="username" type="text" placeholder="user name">
as #Quentin mentioned this not a best practice due to these types of emails such as (.com.au)
but if you really know what you are doing then this code does what you want
// select email input
const mail = document.getElementById('mail');
// add input event
mail.addEventListener('input', e => {
// get value
let value = e.target.value.trim();
const regex = /.com$/ig; // matches any string ends with .com
const result = regex.test(value);
// if matches .com at the end then add focus to name input
if (result) {
e.target.nextElementSibling.focus();
}
});
<form>
<input type="text" placeholder="insert your email" id="mail">
<input type="text" placeholder="insert your name" id="name">
</form>

How to validate my password using a regex in Javascript - code attached evaluates to false everytime

I have the code below and it evaluates to false every time and I don't understand why?
Is this a rookie error on my part? (I'm guessing it must be!) I'm typing a password into the password field on my form every time that starts with 1 uppercase letter, followed by 5 lowercase letters and 2 digits.
I want to regex to test for:
At least 1 uppercase letter
At least 1 lower case letter
At least 1 numerical digit
I've tried editing the regex to take away the start and end anchors and have tried lazy and non lazy matching.
I also originally had the function as a function statement outside the anonymous function block and called it from within the anon function.
This is the html for the form:
<form>
<p>Username:</p>
<input
id="userName"
type="text"
required
name="username"
placeholder="Username"
/>
<p>Password:</p>
<input
id="userPassword"
type="password"
required
name="password"
placeholder="Password"
/>
Forgetten Password?
<input id="submit_btn" type="submit" name="submit_btn" />
</form>
//This is the JS
const validateContainer = {
id: [],
username: [],
password: []
};
document.getElementById("submit_btn").addEventListener("click", function() {
let passwordInput = document.getElementById("userPassword").value;
let passwordRegexp = /^(?=.*?[a-z])(?=.*?[A-Z])(?=.*?[0-9]).{6,}$/;
let passwordTest = passwordRegexp.test(passwordInput);
if (passwordTest) {
alert("Thank you");
validateContainer.password.push(passwordInput);
} else {
alert("Please re-enter password");
}
console.log(passwordTest);
console.log("Button was clicked");
});
I'm expecting the first branch of the if statement to execute, but keep getting the else alter message and console.log(passwordTest) prints false everytime.

Disable user of multiple same exact numbers in input box

I have an input box here
<input type="text" size="9" maxlength="9" id="my_account" name="my_account" value="" >
And I want to disallow users to enter the same numbers in the box? How can I do this ? Thanks in advance
I don't want them to be able to enter numbers like this
111111111
or
55555555
You can use a regular expression to find strings that only consist of one consecutive digit:
var validator = /\b(\d)\1+\b/
console.log(validator.test('111')) // true
console.log(validator.test('123')) // false
console.log(validator.test('121')) // false
console.log(validator.test('112')) // false
#edit If you don't want to let user enter these values as he types you may want to verify only when value equals to 2.
You can listen on keydown event of input element and verify it's actual content and pressed number like this:
var inputNode = document.getElementById('my_account');
inputNode.addEventListener('keydown', (event) => {
var inputValue = event.key;
var inputNodeValue = inputNode.value;
var length = inputNodeValue.length;
if (length === 1 && inputNodeValue[0] === inputValue) {
event.preventDefault();
}
});
If you want to verify on submit, just get value of first character and check if every other is equal to it.
Try this pattern:
<input type="text" size="9" maxlength="9" id="my_account" name="my_account" value="" pattern="^(?!(\d)\1{8}).*">
Notes:
you did not say you wanted to disallow letters, if you do, just replace .* with \d*
I interpreted it as "nine times the same number". If you want to e.g. not allow "3 times same number anywhere", you need to change it to ^(?!\d*(\d)\1{2,}).*
If you want to only disallow multiples of a digit without any other extra, add the line termination regex: ^(?!(\d)\1*$).*
Example for "not 3 times same number anywhere but must be numbers":
<input type="text" size="9" maxlength="9" id="my_account" name="my_account" value="" pattern="^(?!\d*(\d)\1{2,})\d*">
Example for "not only the same number multiple times but still numbers":
<input type="text" size="9" maxlength="9" id="my_account" name="my_account" value="" pattern="^(?!(\d)\1*$)\d*">

set Second validation message

I'm trying to set a Second validation message for my password input, but it doesn't work, can you help me out?
This is my tag:
<input id="password" style="text-align:center;" type="text" name="password"
tabindex="3" pattern="[a-zA-Z0-9].{5,}" title="" required
oninvalid="this.setCustomValidity('Please enter a password')"
oninput="this.setCustomValidity('')"
onkeyup="deleteBadConfirm(); valid_pass();" />
and this is mu js function for the second validation message:
function valid_pass() {
if(document.getElementById("password").value != "") {
document.getElementById("password")
.setCustomValidity('At least, enter 6 characters; Don't use any symbols');
};
};
function deleteBadConfirm() {
$("#confirmpassword").prop("value", "");
};
EDIT: This is how it's supposed to go down:
if the user press submit before entering a password, the message says "please enter a password". Then, if the user enters a password, but it's not valid, this time the message should say"At least, enter 6 ...". Now, it shows the first message, but then, if I enter less than 6 characters, it still brings up the old message, and if I enter 6 invalid characters, it won't show any message!!
You have a error in below line
Change this
document.getElementById("password")
.setCustomValidity('At least, enter 6 characters; Don't use any symbols');
To
document.getElementById("password")
.setCustomValidity('At least, enter 6 characters; Don\'t use any symbols');
by adding a escape character - backslash ()
Clear the oninvalid event or it will always override your setCustomValidity. Added the :invalid CSS pseudo-class to check if value is valid or not.
function valid_pass() {
if (document.getElementById("password").value != "") {
if ($('#password').is(":invalid")) {
document.getElementById("password")
.setCustomValidity('At least, enter 6 characters; Don\'t use any symbols');
};
} else {
document.getElementById("password")
.setCustomValidity('Please enter a password');
};
};
function deleteBadConfirm() {
$("#confirmpassword").prop("value", "");
};
//Added this to show setCustomValidity message/tooltip without submit event
function runReportValidity() {
document.getElementById("password").reportValidity();
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="password" style="text-align:center;" type="text" name="password" tabindex="3" pattern="[a-zA-Z0-9].{5,}" title="" required oninvalid="valid_pass()" oninput="this.setCustomValidity('')" onkeyup="deleteBadConfirm(); valid_pass();" />
<!-- Added this to show setCustomValidity message/tooltip without submit event -->
<input type="button" onClick="runReportValidity()" value="Report Validity">

Categories

Resources