Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate email with a regex in jQuery

Tags:

jquery

Referring to this issue:

How can I set a minimum length for a field with jQuery?,

<form id="new_invitation" class="new_invitation" method="post" data-remote="true" action="/invitations" accept-charset="UTF-8">
    <div id="invitation_form_recipients">
        <input type="text" value="" name="invitation[recipients][]" id="invitation_recipients_0"><br>
        <input type="text" value="" name="invitation[recipients][]" id="invitation_recipients_1"><br>
        <input type="text" value="" name="invitation[recipients][]" id="invitation_recipients_2"><br>
        <input type="text" value="" name="invitation[recipients][]" id="invitation_recipients_3"><br>
    </div>
    <input type="submit" value="Send invitation" name="commit">
</form>

What would the code be for settting a minimum length for a field with jQuery?

$('#new_invitation').submit(function(event) {
    if ($('#invitation_form_recipients input').filter(function() {
        return $(this).val();
    }).length == 0) {
        // All the fields are empty
        // Show error message here

        // This blocks the form from submitting
        event.preventDefault();
    }
});

How can I validate that every field input have a valid email address with jQuery? In the above code?


The Solution!

$('#new_invitation').submit(function(e) { $('#invitation_form_recipients input').each(function(e) { email_address = $(this); email_regex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/i; if(!email_regex.test(email_address.val())){ alert('this is not valid email'); e.preventDefault(); return false; } }); });
like image 907
hyperrjas Avatar asked Mar 05 '12 18:03

hyperrjas


People also ask

How to validate email in jQuery validation plugin?

Now that a method supporting validation against a regular expression was created for the validator, you can use the jQuery. validate as follows: $('#element_id'). validate({ email: { required: true, email: true, regex: /^\b[A-Z0-9.


1 Answers

You probably want to use a regex like the one described here to check the format. When the form's submitted, run the following test on each field:

var userinput = $(this).val();
var pattern = /^\b[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b$/i

if(!pattern.test(userinput))
{
  alert('not a valid e-mail address');
}​
like image 175
rjz Avatar answered Sep 20 '22 22:09

rjz