Whenever we are working with Forms on web pages to submit some data, the Form validations are usually occurring at the server end, i.e. as the user entered all the necessary data and press the Submit button, all the filled data are submitted to server and subsequently validated. If the data entered by the user is incorrect or simply missing, the server sends all the data back to the client and requests for resubmitting of data through form with correct information. This is really a lengthy process which used to put a lot of burden on the server.
Using JavaScript, there are ways to validate most of the form's data on the user system itself before sending it to the web server. This is called Form validation and generally performs two functions:
In this, initially form must be checked to make sure all the mandatory fields are filled in. This is simple and requires a loop through each field in the form to check for data. For Example, Name, Mobile no. and email is mandatory.
In this type of validation, the data entered can be checked for correct format and values (may be some value ranges). It is required that the JS code written must include appropriate logic to test correctness of data. For example, mobile no must be of 10 digits, email must be in correct format or Pin code shall be of 6 digits not starting with zero or Marks obtained shall be between 0 and 100.
Here, we are taking a simple form with only one Name field and enforcing user to fill the name and if name data is not filled and submit button is clicked it will display an alert to the user.
In the example below, a function validateForm() has been created and called to validate data when onsubmit event is occurring.
Code:
Examples
Output: after page is loaded.
Output: after the button is clicked leaving the Name Field blank.
Output: after the button is clicked duly filling the Name Field.
Now we will see how we can validate our entered form data before submitting it to the web server.
Let’s consider a format, which require age must be entered and it shall be 18 or above. However maximum permitted age is 60 years.
In the example below, we have created a JavaScript Function myAge() to check the valid age entry. The function myAge() is called onclick event of Submit button. It will display the message as well as Alert about the Valid or Invalid age entry.
Code:
Examples
Output: after page is loaded.
Output: after the button is clicked filling name in place of age.
Output: after the button is clicked filling the age properly.
Note: You can now run the code to check what happens when age is given out of the specified range.