Javascript form validation example

In this tutorial, you will learn how to validate user input using JavaScript, different type of format, length, type etc.

When user enter data in any form field, we accept that as string form only, so in true sense we validate a string to check if the string containing data as per our business need.

How to validate user input using JavaScript

Let’s assume we have form with some fields, and for each field we have to check if user input is matching with our predefined validation rules.

You probably know there are many built-in validation functions available in jQuery library, which can make the job much easier, however, we trying to use raw JavaScript as much as possible [for learning purpose only].

I am assuming you know how to design html form and pick values from each field, simply use get element by id.

    var _dataInput = document.getElementById("txtId").value;
  • Check if string length is greater than 10 character.
    let _strLength ="WebTrainingRoom";
    if(_strLength.length>10)
        console.log("Yes, length is ok");
    else
        console.log("Length is too short");
    
  • Check if variable is an integer in JavaScript, or string is a valid number!
    let _isNumeric ="100000WTR";
    if (Number.isInteger(_isNumeric))
        console.log("data is integer");
    else
        console.log("data is not an integer");
    

    You also can use parseInt function to check if the data is number!

    let _isNumeric ="100000WTR";
    if (_isNumeric === parseInt(_isNumeric, 10))
        console.log("data is integer");
    else
        console.log("data is not an integer");  
    
  • Check if the data is only text alphabet, there is no integer or special character.

    let _userName="WebTrainingRoom"
    var lettersOnly = /^[A-Za-z]+$/;
    if (_userName.match(lettersOnly))
        console.log('Valid name');
    else 
        console.log('Invalid name');
    
  • Check if string is alphanumeric.

    Alphanumeric mean we want both text and number, and no other character.

    for example "WebTrainingRoom10" is alphanumeric, but "WebTrainingRoom" is not alphanumeric.

    Below JavaScript, function will check if the passed parameter is alphanumeric.

    function CheckAlphaNumeric(stringValue)
       {
        var letterNumber = /^(?=.*[a-zA-Z])(?=.*[0-9])[A-Za-z0-9]+$/;
        if(stringValue.match(letterNumber)) 
            {
                console.log(stringValue + " is AlphaNumeric");
                return true;
            }
        else
            {        
                console.log(stringValue + "  Not AlphaNumeric");
                return false; 
            }
        }
    
    // call the function to check
    CheckAlphaNumeric("WebTrainingRoom1");
    
  • Check if user input is valid email id.

    Note, this type of email validation only can confirm if the email syntax is correct, can’t really validate if the domain exists or email id exists.

    function ValidateEmail(emailId)
    {
    let mailformat = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;
        if(emailId.match(mailformat)){
            console.log("Valid Email");    
            return true;
        }
        else{
            console.log("Invalid Email");    
            return false;
        }
    }
    ValidateEmail("webtrainingroom@gmail.com");
    
  • Check if string has at least one uppercase javascript.

    You can write a function using regular expression like (?=.*[A-Z]), check if matching result found

    function hasUpperCase(inputStr) {
        result=false;
    
        let expression=/(?=.*[A-Z])/;
        if(inputStr.match(expression))
        {
            console.log("Upper case letter found");
            result=true;
        }
        return result;
    }
    
    // test 1
    hasUpperCase("learning Javascript");
    
    // test 2
    hasUpperCase("JavaScript is fun");
    
  • Check if string has at least one lowercase javascript .

    Like above example of finding upper case, you also can find lower case using regular expression (?=.*[a-z]), here are some more expression that can be helpful in finding similar things in JavaScript string.

    • (?=.*[a-z]) find if any lowercase
    • (?=.*[A-Z]) find if any uppercase
    • (?=.*\d) find digit
    • (?=.*\W]) find if any non-word character exists
  • Check if string is valid url in javascript.

    This function can be useful when you want user to enter only url.

    function isValidHttpUrl(string) {
    let url; try {
    url = new URL(string);
    }
    catch (_) {
    console.log("Invalid Url");
    return false; } return url.protocol === "http:" || url.protocol === "https:";
    }
    // test 1
    isValidHttpUrl("badurl.com");
    // test 2
    isValidHttpUrl("http://goodurl.com");
    // test 3
    isValidHttpUrl("https://www.verygoodurl.com");
    
  • Check if string contain a special character!

    Sometimes you may have requirement where you don’t want user not to type some special characters, following function can help you to achieve such requirement.

    function CheckIfSpecialCharacter(inputText)
    {
        var splChars = "*|,\":<>[]{}`\';()@&$#%";
        for (var i = 0; i < inputText.length; i++) 
        {
            if (splChars.indexOf(inputText.charAt(i)) != -1)
            {
                console.log("Special character detected!");
                return false;         
            }
        }
    }
    // test 1
    CheckIfSpecialCharacter("learning at WebTarainingRoom");
    
    // test 2
    CheckIfSpecialCharacter("webtarainingroom@gmail.com");
    

You may be interested in following posts


JavaScript Examples | JavaScript Online Course