3

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>
TylerH
  • 20,799
  • 66
  • 75
  • 101
o'Bass
  • 159
  • 2
  • 18
  • 1
    Have you actually looked for anything or tried anything yourself? – Sam Dec 19 '15 at 23:01
  • Looked yes, but can't find a right peace of code, that only chech A-Z and underscore. – o'Bass Dec 19 '15 at 23:10
  • Learn about regex: http://www.w3schools.com/jsref/jsref_obj_regexp.asp – Sam Dec 19 '15 at 23:14
  • This in your code: if(re = /[a-zA-Z]*_[a-zA-Z]*/;) {...} should be replaced by: re = /[a-zA-Z]*_[a-zA-Z]*/; if (re.test('string_to_validate') {..code to run when string is valid..} – Polak Dec 19 '15 at 23:32

4 Answers4

4

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
Community
  • 1
  • 1
Polak
  • 656
  • 13
  • 22
3

Using regex with jquery:

  • Pass a string to RegExp or create a regex using the // syntax call
  • regex.test(string) not string.test(regex)

In your code:

$(".name").on('keyup', function(e)
{
    var name = $(this).val();
    if(new RegExp(/^[a-zA-Z_]+$/i).test(name)) // or with quotes -> new RegExp("^[a-zA-Z_]+$", 'i')
        $(this).addClass("error");
    else
        $(this).switchClass("error", "success", 1000, "easeInOutQuad");

    e.preventDefault();
    e.stopPropagation(); // to avoid sending form when syntax is wrong
});

And for email input, the following regex can do the job :

/^[+a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/i

Or..

To put a little bit of modernity, you can use html5 email field type

<input type="email" id="email">
MTroy
  • 897
  • 9
  • 20
  • Fixed code, with some perfection :) first, you can test syntax validity without (or before) submit the form – MTroy Dec 19 '15 at 23:28
3

Now using the advanced feature of HTML5 it's eaiser, you can simply do the validation as follow:

 <form action="" method="">
    <!-- Name containing only letters or _ -->
    Name: <input type="text" name="name" pattern="[a-zA-Z][[A-Za-z_]+" /> 
    <!-- using type email, will validate the email format for you-->
    Email: <input type="email" id="email" />
   <input type="submit" value="Submit">
</form> 

Check HERE for more form validation features of HTML5.

Dhia
  • 10,119
  • 11
  • 58
  • 69
  • I made a some new changes but both should work for you. I tested it [here](http://jsfiddle.net/nR6yg/213/embedded/result/) and works fine. – Dhia Dec 20 '15 at 00:49
  • I tried, but seems not working for me :x it skip's the name input than to validate it and check, but Thanks! – o'Bass Dec 20 '15 at 01:03
2

@Polak i tried so, if i understand what you mean :x Sorry i'm new with javascript.

<script type="text/javascript">
    jQuery(document).ready(function($){
        $('[name="submit"]').click(function(e){
            var name = document.getElementById("display_name").value;

            re = /[a-zA-Z]*_[a-zA-Z]*/;
            if (re.test(name) {
                //Things to do when the entry is valid.
                $(".NameCheck").removeClass("name_error");
                $(".NameCheck").addClass("name_success");
                return true;
            } else {
                //Things to do when the user name is not valid.
                $(".NameCheck").addClass("name_error");
                return false;
            });
        });
    });

Polak
  • 656
  • 13
  • 22
o'Bass
  • 159
  • 2
  • 18
  • I'm new with stackoverflow, I've edited your answer, changing if (re.test("name")) {...... by if(re.test(name)){ ...without quotes and the if sentence was inverted. When you define a string variable foo=/...../; like a regex, then you can do things like foo.test('string to test'); and it will return true when the string is accepted by the regex. – Polak Dec 20 '15 at 00:49
  • now i can better understand, Thanks. But i getting Uncaught SyntaxError: Unexpected token { error. But thanks for help! – o'Bass Dec 20 '15 at 01:25
  • i think you forgot by editing from if(re.test(name) { to if(re.test(name)) {. Now it's working. Thanks very much for your help! – o'Bass Dec 20 '15 at 01:30