JavaScript Form Validation

JavaScript Form Validation is a technique used to ensure that the user enters the correct information in a form before submitting it to the server. It helps in providing a smooth user experience by catching errors on the client side and reducing unnecessary server load.

Key Features of JavaScript Form Validation:

Common Validation Techniques:

Code Example: Basic Form Validation

The following example demonstrates a simple form validation that ensures the user enters a name and email address:

Example


<form name="myForm" onsubmit="return validateForm()">
    Name: <input type="text" name="name"><br>
    Email: <input type="email" name="email"><br>
    <input type="submit" value="Submit">
</form>
            
<script type="text/javascript">
    function validateForm() {
        var name = document.forms["myForm"]["name"].value;
        var email = document.forms["myForm"]["email"].value;
        if (name == "" || email == "") 
        {
            alert("Both fields are required.");
            return false;
        }
        return true;
    }
</script>

Output

If the name or email field is left empty, an alert will show "Both fields are required." and prevent the form from submitting.

Explanation of Code:

Advanced Example: Validating an Email Address

This advanced example shows how to validate an email address using a regular expression pattern:

Example


<form name="emailForm" onsubmit="return validateEmail()">
Email: <input type="email" name="email"><br>
<input type="submit" value="Submit">
</form>
            
<script type="text/javascript">
function validateEmail() {
    var email = document.forms["emailForm"]["email"].value;
    var pattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,4}$/;
    if (!pattern.test(email)) {
        alert("Please enter a valid email address.");
        return false;
    }
    return true;
}
</script>

Output

If the email address entered does not match the pattern (e.g., "test@example.com"), an alert will show "Please enter a valid email address." and prevent the form from submitting.

Explanation of Code:

Additional Code Example: Validating Age Range

This example demonstrates how to validate an age input to ensure it is within a specified range (e.g., 18 to 60 years):

Age Validation Example


<form name="ageForm" onsubmit="return validateAge()">
Age: <input type="number" name="age"><br>
<input type="submit" value="Submit">
</form>
            
<script type="text/javascript">
function validateAge()
{
    var age = document.forms["ageForm"]["age"].value;
    if (age < 18 || age > 60) {
        alert("Age must be between 18 and 60.");
        return false;
    }
    return true;
}
</script>

Output

f the age entered is less than 18 or greater than 60, an alert will show "Age must be between 18 and 60." and prevent the form from submitting.

Explanation of Code: