Search code examples
javascriptformvalidation.io

Validations for Password and First name using JavaScript


I am doing form validations and the requirement is 1.Email : Email must be a valid Email ID. 2.Password : Must be eight characters long. Only number(0-9) and letters(A-Z,a-z) are allowed. 3.FirstName : Must not contain any numbers(0-9). 4.LastName : Must not contain any numbers (0-9). I did for email Address and I am struck with the password and FirstName validations.. Can Anyone help me in this Thanks in Advance.

    <form>
            <label for="">First Name</label>
            <input type="text" id="fname"><br>
            <label for="">Last Name</label>
            <input type="text" id="lname"><br>
            <label for="">Email</label>
            <input type="text" id="email"><br>
            <label for="">Password</label>
            <input type="text" id="password"><br>
           <button type="button" onclick="claim()">Claim Your Free Trail</button>
           <p>You Are Agreeing to Our <a href="#">Terms & Condition</a></p>
        </form>

        <script>
            function claim(){
                var obj ={
                    fname:"",
                    lname:"",
                    email:"",
                    password:""
                }

                for(a in obj){
                    obj[a]=document.getElementById(a).value
                }
                if(obj.email.match(/@/) != null){

                }else{
                    alert("Please enter Valid Email Address")
                }
                console.log(obj)
            }
        </script>
    </body>

Solution

  • Password validation

    We use the following regular expression to ensure the password contains only letters and numbers:

    /[^A-Za-z0-9]+/g
    
    • [^] : Matches anything NOT in the set
    • A-Z : Characters in the range "A" to "Z"
    • a-Z: Characters in the range "a" to "z"
    • 0-9: Characters in the range "0" to "9"
    • g: Global flag, allowing inerative search

    So if the password contains non-letters and numbers, the regular expression return true.

    And the whole password validation function as follow:

    function isValidPassword(password) {
        if (
            typeof password !== "string" ||
            password.length !== 8 ||
            /[^A-Za-z0-9]+/g.test(password)
        ) 
            return false;
        return true;
    }
    

    Firstname validation

    We use the following regular expression to check if the password contains any numbers:

    /[0-9]+/g
    
    • [] : Matches anything IN the set
    • 0-9: Characters in the range "0" to "9"
    • g: Global flag, allowing inerative search

    And the whole first name validation function as follow:

    function isValidFirstname(firstname) {
        if (
            typeof firstname !== "string" ||
            /[0-9]+/g.test(firstname)
        ) {
            return false; 
        }
        return true;
    }