Name Validation using Java script

Learn how to write a java script program to validate First Name and Last Name fields with example Program.

Notes

Name should not be blank.

Name should not allow white spaces , numbers and special characters.

<!DOCTYPE html>
<html>
<body>

    First Name: <input type="text" id="fname" onblur="myFunction()">
    <b id="demo1"></b>
    <br />
    <br />
    Last Name: <input type="text" id="lname" onblur="myFunction()">
    <b id="demo2"></b>

    <script>
        function myFunction() {
            debugger;
            var x = document.getElementById("fname");
            var z = document.getElementById("lname");
            var regex = /^[a-zA-Z]{2,30}$/;


            if (x.value == null || x.value == "") {
                document.getElementById("demo1").innerHTML = "Name Cannot be blank";
                x.focus();
                return;
            }

            if (regex.test(x.value)) {
                document.getElementById("demo1").innerHTML = "";
                x.value = x.value.toUpperCase();
            }
            else {
                document.getElementById("demo1").innerHTML = " White space and Special characters and Numbers are not allowed";
                x.focus();
                return;

            }

            if (z.value == null || z.value == "") {
                document.getElementById("demo2").innerHTML = "Name Cannot be blank";
                z.focus();
                return;
            }

            if (regex.test(z.value))
            {
                document.getElementById("demo2").innerHTML = "";
                z.value = z.value.toUpperCase();
            }
            else
            {
                document.getElementById("demo2").innerHTML = "White space and Special characters and Numbers are not allowed";
                z.focus();
                return;
            }


        }
    </script>

</body>
</html>


Leave a Comment