Form Validation
In this document, we have discussed JavaScript Form Validation using a sample registration form. The tutorial explores JavaScript validation on submit with detail explanation.
Following pictorial shows in which field, what validation we want to impose.
How would we set those validations
We will create JavaScript functions (one for each input field whose value is to validate) which check whether a value submitted by user passes the validation.
All those functions are called from another function.
It sets the focus to the input field until the user supplies a valid value.
When the user does so, they may proceed and can supply value to the next available field.
The later JavaScript function created is called on the onsubmit event of the form.
HTML Code of the Sample Registration Form
sample-registration-form-validation.js is the external JavaScript file which contains the JavaScript ocde used to validate the form. js-form-validation.css is the stylesheet containing styles for the form. Notice that for validation, the JavaScript function containing the code to validate is called on the onSubmit event of the form.
For the sake of demonstration, we have taken five countries only. You may add any number of countries in the list.
CSS Code of the Sample Registration Form
JavaScript code for validation
JavaScript function which is called on onSubmit
This function calls all other functions used for validation.
JavaScript function for validating userid
The code above checks whether userid input field is provided with a string of length 5 to 12 characters. If not, it displays an alert.
Flowchart:
avaScript function for validating password
The above code used to validate password (it should be of length 7 to 12 characters). If not, it displays an alert.
Flowchart:
JavaScript code for validating user name
The code above checks whether user name input field is provided with alphabates characters. If not, it displays an alert.
Flowchart:
JavaScript code for validating user address
The code above checks whether user address input field is provided with alphanumeric characters. If not, it displays an alert.
Flowchart:
JavaScript code for validating country
The code above checks whether a country is selected from the given list. If not, then it displays an alert.
Flowchart:
JavaScript code for validating ZIP code
The code above checks whether a ZIP code of numeric value. If not, it displays an alert.
Flowchart:
JavaScript code for validating email format
The code above checks whether a valid email format is supplied. If not,it displays an alert.
Flowchart:
JavaScript code for validating gender
The code above checks whether a sex is selected. If not, it displays an alert. If Male or Female is selected, it generates an alert saying that the form is successfully submitted and it reloads the form.
Flowchart:
Here is the entire JavaScript used for validation of the form.
Flowchart:
No comments:
Post a Comment