JavaScript Form Validation
Form validation normally used to occur at the server, after the client had entered the data and then pressed the submit button. Before submitting data to the server, it is important to ensure all required form controls are filled out, in the correct format. This is called client-side form validation, and helps to ensure that the data submitted matches the requirements set in the various form controls.
Form validation generally performs two functions:
- Basic Validation − First of all, the form must be checked to make sure all the mandatory fields are filled in. It would require just a loop through each field in the form and check for data.
- Data Format Validation − Secondly, the data that is entered must be checked for correct form and value. Your code must include appropriate logic to test correctness of data.
Using Built-in Form Validation
- required: Specifies whether a form field needs to be filled in before the form can be submitted.
- minlength and maxlength: Specifies the minimum and maximum length of textual data (strings)
- min and max: Specifies the minimum and maximum values of numerical input types
- type: Specifies whether the data needs to be a number, an email address, or some other specific preset type.
- pattern: Specifies a regular expression that defines a pattern the entered data needs to follow.
Form validation using JavaScript
We use conditional statements to check whether the form fields are filled according to the specified format.
Validating an input field for non empty values
Before submitting the form, we have to check whether the mandatory fields are filled or not.<script>
function validateForm()
{
var txtfield_val = document.getElementById('txtname').value;
if(txtfield_val == "")
{
alert("Enter value in the text field.");
return false;
}
else
{
return true;
}
}
</script>
<input type="text" id="txtname" name="txtname">
<input type="button" value="submit" onclick="return validateForm()">
Eg: <input type="text" id="txtname" name="txtname" required>
Validating an input field for a required pattern
Email validation:
We use regular expressions to match the email pattern correctly.
<script>
function validateEmail()
{
var email_regexp = /^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
var email_val = document.getElementById('email').value;
if(email_val=="" || !email_val.match(email_regexp))
{
alert("Enter your email correctly.");
return false;
}
else
{
return true;
}
}
</script>
<input type="text" id="email" name="email">
<input type="button" value="submit" onclick="return validateEmail()">
Eg: <input type="email" id="txtname" name="txtname">
Letter validation:
Sometimes we need inputs only as letters, like names. So the input field should accept letters only.
<script>
function validateLetter()
{
var letter_regexp = /^[A-Za-z]+$/; // accepts uppercase or lowercase letters only
var letter_val = document.getElementById('letters').value;
if(letter_val=="" || !letter_val.match(letter_regexp))
{
alert("Enter the letters correctly.");
return false;
}
else
{
return true;
}
}
</script>
<input type="text" id="letters" name="letters">
<input type="button" value="submit" onclick="return validateLetter()">
Number validation:
Sometimes we need inputs only as digits, like phone number, zip/pin, registration number, age etc. For that we need to set the input field to accept digits only.
Following regular expression accepts numbers only.
<script>
function validateNumber()
{
var num_regexp = /^[0-9]+$/; // accepts number only
var num_val = document.getElementById('nums').value;
if(num_val=="" || !num_val.match(num_regexp))
{
alert("Enter the number correctly.");
return false;
}
else
{
return true;
}
}
</script>
<input type="text" id="nums" name="nums">
<input type="button" value="submit" onclick="return validateNumber()">
Eg: <input type="number" id="txtname" name="txtname">
Phone number validation:
Phone numbers may be 7 digits, 10 digits or 12 digits and a standard mobile phone number has 10 digits.
The following regular expression accepts a phone number with 10 digits only.
<script>
function validatePhone()
{
var phone_regexp = /^\d{10}$/; // accepts a 10 digit number only
var ph_val = document.getElementById('phnum').value;
if(ph_val=="" || !ph_val.match(phone_regexp))
{
alert("Enter your phone number correctly.");
return false;
}
else
{
return true;
}
}
</script>
<input type="text" id="phnum" name="phnum">
<input type="button" value="submit" onclick="return validatePhone()">
Validating a Registration Form
Form
<form method="post" action="">
<label for="name">Name: </label>
<input type="text" id="name" name="name"><br><br>
<label for="email">Email: </label>
<input type="text" id="email" name="email"><br><br>
<label for="phone">Phone: </label>
<input type="text" id="phone" name="phone"><br><br>
<label for="addr">Address: </label>
<textarea id="addr" name="addr"></textarea> <br><br>
Gender:
<input type="radio" id="male" name="gender" value="male">
<label for="male">Male</label>
<input type="radio" id="female" name="gender" value="female">
<label for="male">Female</label><br><br>
<input type="submit" value="Submit" onClick="return validateForm()">
</form>
JavaScript Validation for the above Form
function validateForm()
{
var name = document.getElementById('name').value;
var email = document.getElementById('email').value;
var phone = document.getElementById('phone').value;
var address = document.getElementById('addr').value;
var letter_regexp = /^[a-zA-Z\s]*$/; // allows letters and space only
var email_regexp = /^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/; // allows email format only
var ph_regexp = /^\d{10}$/; // allows 10 digits only
if(name=="" || !name.match(letter_regexp))
{
alert("Enter the name correctly.");
return false;
}
else if(email == "" || !email.match(email_regexp))
{
alert("Enter the email correctly.");
return false;
}
else if(phone == "" || !phone.match(ph_regexp))
{
alert("Enter the phone number correctly.");
return false;
}
else if(address == "")
{
alert("Enter your address.");
return false;
}
else if(address == "")
{
alert("Enter your address.");
return false;
}
else if(document.getElementById('male').checked == false && document.getElementById('female').checked == false)
{
alert("Select your gender.");
return false;
}
else
{
return true;
}
}
</script>