Search code examples
javascripthtmljqueryregexvalidation

Name,Email Validation


I'm looking for code that validates the Name and Email input's on <Form onsubmit="return validate();">

I want that username has only A-Z,a-z and must have an underscore_, email should have an @. How can I do it with jQuery?

Form(example):

<html>
    <head>
    <title>TEST</title>
    </head>
    <body>
    <form action="..." method="POST" onSubmit="return Check()" >
    <input type="text" id="name" placeholder="Please enter your Name. (Must have underscore)" required>
    <input type="text" id="email" placeholder="E-Mail">
    <input type="submit" value="submit">
    </form>
    </body>
</html>

I've tried:

<script type="text/javascript">
        jQuery(document).ready(function($){
            $('[name="submit"]').click(function(e){
            var name = document.getElementById("name").value;
            if(re = /[a-zA-Z]*_[a-zA-Z]*/;) {
                $(".name").addClass("error");
                return false;
            } else {
                $(".name").removeClass("error");
                $(".name").addClass("success");
                return true;
            }
            });
        });
</script>

Solution

  • For a valid email address: Validate email address in JavaScript?

    For your username is the same but your regex should be something like this:

    re = /^[a-zA-Z]*_[a-zA-Z]*$/; //this always needs an underscore to be valid.
    

    Just in case, this is the regex to accept anything az AZ and _ and nothing, it depends on your requirements:

    re = /^[a-zA-Z_]*$/;
    re = /^[a-zA-Z_]{3,}$/; //3 or more chars
    

    To test your regex:

    re = /^[a-zA-Z_]*$/;
    return re.test('any_string_to_test'); //it returns true if your string is valid