JavaScript Validation : An Overview of Client Side Validation
JavaScript is a client-side scripting language, which means that the the script runs on the your viewer or client’s browser and not on the server. JavaScript extends the web functionality with a combination of HTML and server side languages. JavaScript validation is one of the common features used with the language. Interactive websites contains dynamic content that requires user input and such user input is then authenticated before submitting to the processing page. Validation refers to a specific check, which makes the user enter the correct information, or information in a correct format as required by the site. For instance, if a phone number is required, then the user might enter a alphanumeric value by mistake, which is not possible in the case of phone numbers. Using JavaScript validation prevents these mistakes from passing on to your database.
Validation is made up of two types: real-time validation and on-submit validation. Regardless of what you validate in JavaScript, you have to choose between real-time validation or on-submit validation. Real-time validation checks the data with every keystroke or once the field in question loses focus. On-submit validation waits until the user hits the submit button.
Learn JavaScript from scratch by taking a course at Udemy.com
A basic null validation code block uses an ‘if’ condition to check whether a specific HTML element returns a value. The following example checks to see if the user entered any value at all:
if( document.Form_validate.Name.value == "" ) { alert( "Please provide your name!" ); document.Form_validate.Name.focus() ; return false; }
Data that you can validate using JavaScript includes:
- Required fields
- Username
- Password
- Email address
- Phone number
You usually create a separate JavaScript function for validation. You can then make calls to other functions to validate different form fields. Each validation function should return an error message if the input is invalid.
The main JavaScript function looks like the following:
function validateFormOnSubmit(Form_validate) { var error_message = ""; // Different Functions for validation of different input error_message = validUsername(Form_validate.username); error_message = validPassword(Form_validate.psd); error_message = validEmail(Form_validate.email); error_message = validPhone(Form_validate.phone); error_message = validEmpty(Form_validate.from); if (error_message != "") { alert("Some fields have invalid entry :\n" + error_message); return false; } return true; }
Empty Field Check
In this example, you can check that any required field is not left blank by the user. If the field is empty, an error message is displayed.
Example:
function validEmpty(fd) { var error = ""; if (fd.value.length == 0) // Condition is checked if field is left blank { fd.style.background = 'Red'; error = "The required field is empty.\n" //error message is displayed if field is blank } else { fd.style.background = 'White'; } return error; }
UserName Validation
New to JavaScript? Take a class at Udemy.com to learn more.
The username validation depends and changes from website to website as set by the developer. Generally, regular expressions are used to check the input value in the validation form. The username is required to check two things:
- That the input is not blank
- Input contains the minimum or maximum characters required
Example:
function validUsername(fd) { var error = ""; var illegalChars = /\W/; // No special Characters allowed if (fd.value == "") { fd.style.background = 'Red'; error = "Field is left Blank.\n"; } else if ((fd.value.length < 5) || (fd.value.length > 15)) // Number of Character entered is checked { fd.style.background = 'Red'; error = "Username is should be in a range of 5 and 15..\n"; } else if (illegalChars.test(fd.value)) // check for illegal characters { fd.style.background = 'Red'; error = "Illegal Characters not allowed\n"; } else { fd.style.background = 'White'; } return error; }
Password Validation
The basic validation for passwords is that it should not be empty and a minimum length of characters is necessary. Regular expressions for alphanumeric values used are is “/(a-z)+/” and “/(0-9)/”.
Example
function validPassword(fd) { var error = ""; var illegalChars = /[\W_]/; // Numbers and letter only if (fd.value == "") { fd.style.background = 'Red'; error = "Field Cannot be blank.\n"; } else if ((fd.value.length < 7) || (fd.value.length > 15)) // Checks length of the password { error = "Length should be in Range of 7 to 15. \n"; fd.style.background = 'Red'; } else if (illegalChars.test(fd.value)) { error = "Illegal characters not allowed.\n"; fd.style.background = 'Red'; } else if (!((fd.value.search(/(a-z)+/)) && (fd.value.search(/(0-9)+/)))) // Checks for numeric value in entered password { error = "Atleast one Numeric value Required "; fd.style.background = 'Red'; } else { fd.style.background = 'White'; } return error; }
Validating Email
The most important challenge for a developer is to validate an email address as it contains combinations of special character such as the @, dot(.) and alphanumeric values.
Other constraints are that the “@” should be present only once and should not be the first character of the email address. You can use a regular expression that contains the necessary constraints.
All the whitespaces are trimmed and the resultant string is tested for email validation.
function trim(s) // Trims spaces { return s.replace(/^\s+|\s+$/, ''); } function validEmail(fd) { var error=""; var tfd = trim(fd.value); // Calling the trim Function var email_filter = /^[^@]+@[^@.]+\.[^@]*\w\w$/ ; // Valid Email address Regular Expression var illegalChars= /[\(\)\<\>\,\;\:\\\"\[\]]/ ; // Invalid input for the email address if (fd.value == "") { fd.style.background = 'Red'; error = "Field Cannot be Blank.\n"; } else if (!email_Filter.test(tfd)) //Illegal Characters check { fd.style.background = 'Red'; error = "Enter valid Email \n"; } else if (fd.value.match(illegalChars)) // Checks for illegal characters { fd.style.background = 'Red'; error = "Illegal Characters Present.\n"; } else { fd.style.background = 'White'; } return error; }
Validating Phone Number
When it comes to a phone number, the only constraint is that it contains only digits and the number of digits depends on the country. For the US, the phone number input requires 10 digits.
function validPhone(fd) { var error_message = ""; var strip = fd.value.replace(/[\(\)\.\-\ ]/g, ''); //Regular expression for illegal character check if (fd.value == "") { error_message = "Field cannot be Blank.Enter a phone number.\n"; fd.style.background = 'Red'; } else if (isNaN(parseInt(strip))) { error_message = " Illegal characters cannot be Present.\n"; fd.style.background = 'Red'; } else if (!(strip.length == 10)) { error = "Enter the valid Phone Number.\n"; fd.style.background = 'Red'; } return error; }
HTML Form
An HTML form has a submit button that prompts the browser to send data to your processing page. When your user clicks the button, JavaScript validation is called to check for valid input. If input is valid, the form submits. If not, an error message is displayed and the user has to re-enter data. JavaScript validation stops the form from submitting as well.
HTML form Example for Validation:
<form name="myForm" action="demo_form.asp" onsubmit="return validateForm();" method="post"> Username: <input type="text" name="username"> <br /> Email: <input type="text" name="email"> <br />
Password: <input type="text" name="password"> <br />
Phone Number: <input type="text" name="number"> <br />
<input type="submit" value="Submit"> </form> </body> </html>
The “onsubmit” event tells the browser what function to execute when the user clicks the submit button. If the “validateForm()” function returns false, then submission stops and the user is prompted to fix the incorrect data. If all fields are filled out properly, the data is passed to the demo_form.asp processing page.
Learn advanced JavaScript programming with a tutorial at Udemy.com
Recommended Articles
Top courses in JavaScript
JavaScript students also learn
Empower your team. Lead the industry.
Get a subscription to a library of online courses and digital learning tools for your organization with Udemy Business.