Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
33 views

JavaScript Form Validation

Uploaded by

dhamip333
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views

JavaScript Form Validation

Uploaded by

dhamip333
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 15

JavaScript Form Validation

It is important to validate the form submitted by the user because it can have inappropriate values.
So, validation is must to authenticate user.
It is important to validate the form submitted by the user because it can have inappropriate values.
So, validation is must to authenticate user.
It is important to validate the form submitted by the user because it can have inappropriate values.
So, validation is must to authenticate user.
It is important to validate the form submitted by the user because it can have inappropriate values.
So, validation is must to authenticate user.

Using client side JavaScript is an efficient way to validate the user input in web applications. When there are
many fields in the form, the JavaScript validation becomes too complex.

The JavaScript class presented here makes the form validations many times easier.

The idea is to create a set of "validation descriptors" associated with each element in a form. The "validation
descriptor" is nothing but a string specifying the type of validation to be performed.

Each field in the form can have 0, 1, or more validations. For example, the input should not be empty, should be
less than 25 chars, should be alpha-numeric, etc

A particular aspect of validation in Javascript will be discussed in this section, and that is forms.
An example from real life will help us to understand the situation. As you might have filled out a lot of forms
on the web applications, let's say you are trying to login into the application and you entered the incorrect email
address or you did not provide a password, then you will be given an error message that the email is invalid or
the password field is empty. All of these kinds of validations are performed by Javascript.

STEP1: Creating the HTML Form

We can create an HTML form by using the HTML tags related to forms, like, form, input, etc.

<form>

<!-- Write Your Form Here -->

</form>

STEP2: Adding Style Sheet to Beautify


the Form
STEP3: Building the Form Validation Script

Scripts are small pieces of code written in Javascript either in a script tag or in a separate file for some short
automated process. With the Javascript form validation script, we can validate several input fields to ensure that
user data is authentic. The script specifies when a request is to be sent to the server, obviously after the
validations of user data.

JavaScript Form Validation Examples

In this example, we will check for several form input fields like,

 Name should neither be null or blank nor consists of less than 3 characters.
 Password should neither be null or blank nor consists of less than 6 characters. Also, both passwords
must match.
 Image must be of gif, png, or jpeg extension.
 Phone Number must contain all numeric values.
 Email must be correct(Further explanation of provided regex is given below).

 JavaScript Name Validation

This javascript function will accept a name variable and will check whether it is null or blank, subsequently, it
will check for the length of the name, which should not be less than 3.

function validateName(name) {

if (name == null || name == "") {

alert("Name can't be blank!");

return false;

if (name.length < 3) {

alert("Name must be atleast 3 characters long!");

return false;
}

return true;

 JavaScript Re-Type Password Validation

This javascript function will compare the two provided passwords.

function confirmPassword(password, confirm_password) {

if (password ==! confirm_password) {

alert("Entered Passwords are not Same!");

return false;

return true;

 JavaScript Number Validation

This function will check whether the given input is a number or not. In javascript, we have an inbuilt
function isNaN() which returns true if the provided argument is a number.

function validateNumber(number) {

if (isNaN(number)) {

alert("Only Numeric Values are allowed!");

return false;

return true;

 JavaScript Email Validation

This function will accept an email string as a parameter and test it against a regex pattern to ensure that provided
string is a valid email. Below is the description of RegExp Pattern,

 ^ denotes the starting of the string.


 [a-zA-Z0-9_.] denotes that characters from a-z, A-Z, 0-9, and _ are allowed.
 + denotes that the previous pattern could occur one or several times.
 @ will check for an exact match.
 [a-zA-Z0-9.] again it will check for a-z, A-Z, 0-9, and ..
 + denotes that the previous pattern could occur one or several times and subsequent $ denotes
the end of the Pattern.

function validateEmail(email)

var reg = new RegExp("^[a-zA-Z0-9_.]+@[a-zA-Z0-9.]+$");

if (!reg.test(email)) {

alert("Invalid e-mail Address!");

return false;

return true;

NOTE:

 Client-side validations are performed in order to protect our server from invalid data.
 A server cannot respond correctly if the incoming data is not well-formatted; it is, therefore,
necessary to validate the data.
 In Javascript, we can validate a form by writing a script and then attaching the script to the
submit button's on-click event.
 If the script can determine the validity of the data, then only the server requests will be executed.

EXAMPLE:

<!DOCTYPE html>

<html>

<link href="./mystyles.css" rel="stylesheet" />


<script>

function validateName(name) {

if (name == null || name == "") {

alert("Name can't be blank!");

return false;

if (name.length < 3) {

alert("Name must be atleast 3 characters long!");

return false;

return true;

function validatePassword(password, confirm_password) {

if (password == null || password == "") {

alert("Password can't be blank!");

return false;

if (password.length < 6) {

alert("Password must be at least 6 characters long!");

return false;

return confirmPassword(password, confirm_password);

function confirmPassword(password, confirm_password) {

console.log(password, confirm_password)

if (password === confirm_password) {

return true;
}

else {

alert("Entered Passwords are not Same!");

return false;

function validateImage(file) {

var fileName = file.value.split("\\").pop();

var allowedExtensions = /(\.jpg|\.jpeg|\.png)$/i;

if (!allowedExtensions.exec(fileName)) {

return false;

return true;

function validateEmail(email) {

var reg = new RegExp("^[a-zA-Z0-9_.]+@[a-zA-Z0-9.]+$");

if (!reg.test(email)) {

alert("Invalid e-mail Address!");

return false;

return true;

function displayFileName(file) {

var fileName = file.value.split("\\").pop();

document.getElementById("fileDescription").innerHTML = fileName;

document.getElementById("fileDescription").style = "color:blue";
}

function validateNumber(number) {

if (isNaN(number)) {

alert("Only Numeric Values are allowed!");

return false;

return true;

function validateImage(filePath) {

var allowedExtensions = /(\.jpg|\.jpeg|\.png)$/i;

if (!allowedExtensions.exec(filePath)) {

alert("Invalid Image Provided!")

return false;

return true;

function validateForm() {

let isValid = true;

if (!validateName(document.signup.fname.value)) {

isValid = false;

if (!validateName(document.signup.lname.value)) {

isValid = false;

if (!validatePassword(document.signup.password.value, document.signup.confirm_password.value))
{
isValid = false;

if (!validateEmail(document.signup.email.value)) {

isValid = false;

if (!validateNumber(document.signup.phone.value)) {

isValid = false;

if (!validateImage(document.signup.file.value)) {

isValid = false;

isValid ? alert("Form Data is Valid") : alert("Form Data is not Valid")

</script>

<body>

<form name="signup" method="post">

<div>

<div class="heading">Sign Up Form</div>

<hr>

<div class="flex">

<div class="flexItem">

<label class='label' for="fname">First name</label><br>

<input class='input' type="text" id="fname" name="fname"><br>

</div>

<div class="flexItem">

<label class='label' for="lname">Last name</label><br>


<input class='input' type="text" id="lname" name="lname"><br>

</div>

</div>

<div class="flex">

<div class="flexItem">

<label class='label' for="email">Email</label><br>

<input class='input' type="email" id="email" name="email"><br>

</div>

</div>

<div class="flex">

<div class="flexItem">

<label class='label' for="phone">Phone</label><br>

<input class='input' type="phone" id="phone" name="phone"><br>

</div>

</div>

<div class="flex">

<div class="flexItem">

<label class='label' for="password">Password</label><br>

<input class='input' type="password" id="password" name="password"><br>

</div>

<div class="flexItem">

<label class='label' for="password">Confirm Password</label><br>

<input class='input' type="password" id="confirm_password"


name="confirm_password"><br>

</div>

</div>

<div class="flex">

<div class="flexItem">
<button class='upload'

onclick="event.preventDefault(); document.getElementById('file').click()">Profile

Picture</button>

<input type='file' id="file" name='file' onchange="displayFileName(this)"


style="display:none">

</div>

<div class="flexItem" id="fileDescription">

</div>

</div>

</div>

<input class="submit" type="submit" value="Submit" onclick=" event.preventDefault();


validateForm()">

</div>

</form>

</body>

</html>

EXAMPLE 2: BASED ON USING REGULAR EXPRESSION

<html>

<head><title>validation form </title>

<script language="javascript">

function f1(w)

var exp=/[\w]{6,9}[@][\w]{4,5}[.][a-z]{3,4}$/;

var res=exp.test(w);

if(!res)
{

alert("must be valid email address");

return false;

else

return true;

function f2(x)

var exp=/^[\d]{6,8}$/;

var res=exp.test(x);

if(!res)

alert(" password must contain six to eight digits only");

return false;

else

return true;

function f3(y)

var exp=/^$/;

var res=exp.test(y);

if(!res)

alert("empty must be empty");

return false;

else

return true;

function f4(z)

var exp=/(?=^.{9,}$)(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?!.*\s)[0-9a-zA-Z]*$/;
var res=exp.test(z);

if(!res)

alert(" username must contain atlest one digit ,one small ,one capital letter and must contain more than eight
characters");

return false;

else

return true;

function fun(e,p,um,u)

var em=e.value;

var pwd=p.value;

var empt=um.value;

var usr=u.value;

if((em=="")&&(pwd=="")&&(empt=="")&&(usr==""))

alert("all fields can't be blank ");

return false;

if(em=="")

alert("email can't be blank");

return false;

if(pwd=="")

alert("password can't be blank");

return false;

/*if(empt!="")

alert("empty must be empty");


return false;

}*/

if(usr=="")

alert("username can't be blank");

return false;

a=f1(em);

b=f2(pwd);

c=f3(empt);

d=f4(usr);

if((b==true)&&(d==true)&&(c==true)&&(a==true))

alert("ok");

return true;

else

alert("not ok");

return false;

</script>

</head>

<body >

<form name="frm" onSubmit="return fun(this.eml,this.pass,this.emp,this.user)" >

Email:<br>

<input type="text" name="eml"><br>

Password:<br>

<input type="password" name="pass"><br>

Empty:<br>

<input type="text" name="emp"><br>

Username:<br>
<input type="text" name="user"><br>

<input type="submit" name="Submit" value="Submit">

</form>

</body>

</html>

const isEmailValid = (email) => {


const re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.
[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
};

const isPasswordSecure = (password) => {


const re = new RegExp("^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#\$%\^&\*])(?=.{8,})");
return (password);
};

Or

 (?=.*\d) asserts that the password must contain at least one digit.
 (?=.*[a-z]) asserts that the password must contain at least one lowercase English character.
 (?=.*[A-Z]) asserts that the password must contain at least one uppercase English character.
 (?=.*[!@#$%^&*()\-+.]) asserts that the password must contain at least one special character from the
specified set.
 .{6,20} specifies that the password must be between 6 and 20 characters in length.

function validateEmail(email)

var reg = new RegExp("^[a-zA-Z0-9_.]+@[a-zA-Z0-9.]+$");


if (!reg.test(email)) {

alert("Invalid e-mail Address!");

return false;

return true;

/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/

You might also like