Updated March 31, 2023
Introduction to JavaScript Validator
The following article provides an outline on JavaScript Validator. We often use forms for accepting user inputs and processing on the entered data while developing a software application. However, it is necessary to accept correct data which can be processed further. For this purpose, validation is a necessary caution that you should take while developing software.
Most of the projects are in the client-server format, where data is accepted from the user on client-side and a request is fired from there containing the accepted data and sent to the server. The server then processes the received data in the request and sends back the response along with the necessary information to be retrieved and processed at the client-side. To continue this request-response play fluently and correctly, the most important thing is that the data which is sent as input to the server is validated properly so as a resultant thing server can send the appropriate response to the client.
What is Validation?
Validation is nothing but checking the correctness of the entered values and verifying the same. Validations can be done in two ways namely, Server-side validation and client-side validation.Both have their advantages and disadvantages. Server-side validations should be used when you have to validate the data based on available data in your database.
For example, while creating a new account the entered username needs to be validated against the already existing usernames in the database. If the username already exists which matches the entered one the user should be asked to reenter another username.There are some validations like the specified fields are compulsorily to be entered or the entered field must be in a numeric format or entered date field should be in the correct format. All these validations don’t have database dependency involved with them. If server-side validations are used then the request-response cycle can majorly affect our performances. Hence, in this case, Client-side validations should be used.
JavaScript Validations on Client-Side
In web-based environments, JavaScript can be used for client-side validation. It can make sure that the sent data to the server is clean, correct and well-formatted. The Document interface of JavaScript has one read-only property named forms which returns a collection containing all forms in the document scope.
It is accessed as follows:
Collection of forms in Dom = document.forms;
To access the individual elements of a particular form i.e single form object which is represented by HTMLFormElement object, we can use elements property of HTMLFormElement as follows:
HTMLFormElement.elements[index];
Required Field Validation Using Javascript
Example:
Code:
<html>
<body>
<h1 style="text-align: center"> Let’s Learn Javascript Validations </h1>
<form name="UserForm" onSubmit="return validateData()" method="post">
<p> User’s Name: <input type="text" size=50 name="userName"></p>
<p> Address: <input type="text" size=80 name="userAddr"></p>
<p>
Select Your Gender
<select type="text" value="" name="gender">
<option>None</option>
<option>Male</option>
<option>Female</option>
</select>
</p>
<br></br>
<p>
<input type="submit" value="Submit" name="Submit Form">
<input type="reset" value="Reset" name="Reset Form">
</p>
</form>
</body>
<script>
function validateData() {
let userForm= document.forms["UserForm"];
let uname= userForm.elements["userName"];
let name = document.forms["UserForm"]["userName"];
let address = document.forms["UserForm"]["userAddr"];
let gender = document.forms["UserForm"]["gender"];
if (name.value == "")
{
window.alert("Please enter your name.");
name.focus();
return false;
}
if (address.value == "")
{
window.alert("Please enter your address.");
address.focus();
return false;
}
if (gender.selectedIndex< 1)
{
alert("Please enter your gender.");
gender .focus();
return false;
}
return true;
}
</script>
</html>
Output:
Here, the user form variable is HTMLFormElement object which represents the whole UserForm form. And it’s elements are accessed by.Elements[index] property. So we can conclude that both uname and name are the same fields.
So a single field can be accessed in two ways:
document.forms[index of form][index of element];
document.forms[index].elements[index];
After running your program, if you directly press submit button it will validate the first field which is not entered which is name and hence will give an alert mentioning you have to enter this field and after you say ok the focus will be on the name field as we have written name.focus(); after alert message. Note that the sequence in which you code for validations in the script tag matters. Field displayed first should be validated first and later one should be validated next. If not done so, functionality won’t be affected but the sequence of focus and checking should always be from up to down navigating each field.
Other Validations Using JavaScript
Here instead of just checking whether fields are empty, we can also check other validations like whether the field entered is number by using isNaN() or specific formats like email or mobile number using regular expressions(For more information about regular expressions refer https://www.regular-expressions.info/).
Code:
<html>
<body>
<h1 style="text-align: center"> Let’s Learn JavascriptValidations </h1>
<form name="UserForm2" action="/submitData.php" onsubmit="return validateData()" method="post">
<p> Password: <input type="text" size=50 name="password"></p>
<p> Confirm Password: <input type="text" size=80 name="matchPassword"></p>
<p> Age <input type="text" size=25 name="age"></p>
<p> Email Id: <input type="text" size=20 name="emailId"></p>
<p> Mobile No: <input type="text" size=15 name="mobNo"></p><br>
<p><input type="submit" value="Submit" name="Submit Form">
<input type="reset" value="Reset" name="Reset Form">
</p>
</form>
</body>
<script>
function validateData()
{
var password = document.forms["UserForm2"]["password"];
varmatchPassword = document.forms["UserForm2"]["matchPassword"];
var age = document.forms["UserForm2"]["age"];
varemailId = document.forms["UserForm2"]["emailId"];
varmobNo = document.forms["UserForm2"]["mobNo"];
if (password.value=="" || matchPassword.value=="" || (password.value != matchPassword.value))
{
window.alert("'Confirm Password' should be same as entered 'Password'.");
matchPassword.focus();
return false;
}
if (age.value=="" || isNaN(age.value) || age.value<0 || age.value>150)
{
window.alert("Entere valid age in number format.");
age.focus();
return false;
}
varemailIdRegex =/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if (emailId .value=="" || !(emailIdRegex .test(emailId .value)))
{
window.alert("Please enter valid e-mail Id.");
emailId .focus();
return false;
}
varmobileNoRegex = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;
if(mobNo.value=="" || !(mobNo.value.match(mobileNoRegex)))
{
window.alert("Please enter your mobile number.");
mobNo .focus();
return false;
}
return true;
}
</script>
</html>
Output:
In the above application is NaN() function is used for checking whether the entered string is Not A Number(NAN). test() and match functions are used to check whether the value of the field is parsable in the regular expression mentioned while testing or matching. In this way, we can validate our form fields on the client-side and avoid the bandwidth usage and increase the performance of our application. Using javaScript we can validate multiple fields and apply constraints according to our requirements.
Recommended Articles
This is a guide to JavaScript Validator. Here we discuss the introduction, what is validation? and JavaScript validations on client-side. You may also have a look at the following articles to learn more –