Menu Close

Validating your form using core javascript

JavaScript is used for mainly client-side validations. A form is also called a web form or HTML form. Forms are used on web pages for users to enter their required details, which are sent to the server for processing. For example, Student registration form, online banking, ecommerce sites, etc.

Below is a code in HTML, CSS and JavaScript to verify a form. HTML is used to create the form. CSS is designing the layout of the form. JavaScript to check the form.

Here is my HTML code for this.

  1. <!DOCTYPE html>    
  2. <html>    
  3. <head>    
  4.     <title>Reg Form</title>   
  5. <script src=”validator.js”></script> 
  6. </head>    
  7. <body>    
  8.     <center><h1>Form Validation using HTML,CSS,JavaScript</h1></center>  
  9.  
  10. <form method=”” action=”” name=”form1″ onsubmit=”return validate()”>

<h2>Registration Form</h2>

<label>First Name: </label>

<input type=”text” name=”fname” placeholder=”First Name”> 

<br>

<label>Last Name: </label>

<input type=”text” name=”lname” placeholder=”Last Name”>  

<br>

<label>Address: </label><br>

<input type=”textarea” size=”50″ name=”address” placeholder=”Address”> 

<br>

<label>Gender: </label>

<input type=”radio” name=”gender” value=”male”>Male 

<input type=”radio” name=”gender” value=”femele”>Female    

</form>

Here is my CSS code for this.

After applying the CSS code, the form will change to a responsive format. 

Try it yourself,

  1. <style type=”text/css”>  
  2.     body{  
  3.         font-family: Calibri;  
  4.     }  
  5.     input[type=”text”] {  
  6.         width: 250px;  
  7.     }  
  8.     form{  
  9.         text-align: center;  
  10.         font-family: Calibri;  
  11.         font-size: 20px;  
  12.         border: 3px solid black;  
  13.         width: 600px;  
  14.         margin: 20px auto;  
  15.     }  
  16. </style>

Here is my JavaScript code for this.

After we have successfully created the form, the next step is to validate the form using JavaScript. Well, let’s create a JavaScript file named “validator.js” and place the following code inside it, then save it at the same location where you’ve saved the previous HTML file. Go through each line of the following example code to understand how JavaScript validation works:


Try it yourself.

function validateForm() { // Retrieving the values of form elements var name =

document.form1.fname.value;

printError(“Please write your fname”)

document.form1.fname.focus();

return false;                }

document.form1.lname.value==””;

printError(“Please write your fname”)

document.form1.fname.focus();

return false;   

document.form1.address.value==””;

printError(“Please write your fname”)

document.form1.fname.focus();

return false;   

 document.form1.gender.value==””;

printError(“Please write your fname”)

document.form1.fname.focus();

return false;   

</script>

The value of an individual form field can be accessed and retrieved using the syntax document.form1.fieldName.value or document.getElementsByName(name).value. But, to get the values from a form field that supports multiple selections, like a group of checkboxes, you need to utilize the loop.

Also, to check whether the format of input data is correct or not we’ve used the regular expressions. It is one of the most effective techniques for validating the user inputs.

Furthermore, the above script will also display the data entered by the user in an alert dialog box for preview purpose before submitting the form to the web server.

Using reg expression to validate form in js

A regular expression is a pattern that could be matched against an input text. The following is the important list of regular expressions that we use widely in our applications.

  1. Email id validation
  2. URL validation
  3. Password strength validation
  4. Mobile number validation
  5. String pattern validation

For using a regular expression in C# server side, we need to use the following namespace.

using System.Text.RegularExpressions;

Remember to remove / at the start and the end of the string to convert a JavaScript Regex to C#.

1. Email id validation regular expression

Regular expression:

  1. /^\w+([-+.’]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/ (Email Id)
  2. /^([\w-\.]+@(?!gmail.com)(?!yahoo.com)(?!hotmail.com)([\w- ]+\.)+[\w-]{2,4})?$/ (free/domain specific email id)

2. URL validation regular expression

Regular expression:

  1. /(http(s)?://)?([\w-]+\.)+[\w-]+[.com]+(/[/?%&=]*)?/ (with or without http)

  2. /((www\.|(http|https|ftp|news|file)+\:\/\/)[_.a-z0-9-]+\.[a-z0-9\/_:@=.+?,##%&~-]*[^.|\’|\# |!|\(|?|,| |>|<|;|\)])/( valid everywhere)

3. Password strength validation regular expression

Regular expression:

  1. / ^[a-z0-9\.@#\$%&]+$/ (only contains letter [a-z] digits[0-9], special characters(@#$%&))

  2. / ^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$/ (Minimum 8 characters at least 1 Alphabet and 1 Number)

  3. / ^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[$@$!%*?&])[A-Za-z\d$@$!%*?&]{8,}/ (Minimum 8 characters at least 1 Uppercase Alphabet, 1 Lowercase Alphabet, 1 Number and 1 Special Character)

  4. / ^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[$@$!%*?&])[A-Za-z\d$@$!%*?&]{8,10}/ (Minimum 8 and Maximum 10 characters at least 1 Uppercase Alphabet, 1 Lowercase Alphabet, 1 Number and 1 Special Character)

  5. / ^[a-zA-Z0-9\s]{7,16}$/ (Minimum length 7 and Maximum length 16 Characters allowed [a–z] [A-Z] [0-9])

4. Mobile number validation regular expression

Regular expression:

  1. / ^((\+){0,1}91(\s){0,1}(\-){0,1}(\s){0,1}){0,1}9[0-9](\s){0,1}(\-){0,1}(\s){0,1}[1-9]{1}[0-9]{7}$/ (without +91 or 0)

  2. /^((\\+91-?)|0)?[0-9]{10}$/ (with or without +91 or 0)

  3. ^((\\+|00)(\\d{1,3})[\\s-]?)?(\\d{10})$/ (split the number and the country code)

5. String pattern validation regular expression

Regular expression:

  1. /(?s)^((?!manish).)*$/ (string contains manish)
  2. \d/ (at list one digit )
  3. /(.)*(\\d)(.)* / (contains number)
  4. /^\d$/ (contains only number )
  5. /^\d{11}$/ (contains only 11 digit number )
  6. /^[a-zA-Z]+$/ (contains only letter )
  7. /^[a-zA-Z0-9]+$/ (contains only letter and number )

Use of the regular expressions

Use the preceding regular expressions in the following ways.

In the following example, I am showing an email validation in various ways. Just replace the regular expression and use any of the others to use another validation.

Using JavaScript

  1. <script type=”text/javascript”>  
  2.          function validateEmailId(email) {  
  3.              var reg = regular expression above pattern  
  4.              if (reg.test(email)) {                   
  5.                  mesg.innerHTML = “”;  
  6.                  return true;  
  7.              }  
  8.              else {  
  9.                  mesg.style.color = “red”;  
  10.                  mesg.innerHTML = “Please provide a valid email address”;   
  11.                  return false;  
  12.              }  
  13.          }  
  14.     </script>  

Nesting your individual input validation function in a major function that is checked on form submission

Leave a Reply

Your email address will not be published. Required fields are marked *