5

I'm using the following code (with jQuery Validation Plugin) to validate an email address:

    $(".schedule-tour-form").validate({
        rules: {    
            Email: {
                required: true,
                email: true
            }       
        },
    });

    <input id="email" name="Email" class="email" type="email" placeholder="name@email.com" />

Problem is it still allows emails without domain suffixes. For example it validates "test@test" How to I require a domain suffix?

Sparky
  • 98,165
  • 25
  • 199
  • 285
Sam
  • 5,150
  • 4
  • 30
  • 51

1 Answers1

3

The official page of plugin, even consider test@test as a valid mail, then I suppose that this is intended. You could create a new rules, with a strict regex pattern, as suggested here.

//custom validation rule
$.validator.addMethod("customemail", 
    function(value, element) {
        return /^([a-zA-Z0-9_.-+])+\@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/.test(value);
    }, 
    "Sorry, I've enabled very strict email validation"
);

Then to your rules add:

rules: {
                    email: {
                        required:  {
                                depends:function(){
                                    $(this).val($.trim($(this).val()));
                                    return true;
                                }   
                            },
                        customemail: true
                    },
Community
  • 1
  • 1
BAD_SEED
  • 4,840
  • 11
  • 53
  • 110
  • 1
    The regex in the answer did not work for me. Turned out that hyphen has special meaning in the regex syntax so need to escape it. Updated Regex: /^([a-zA-Z0-9_.\-+])+\@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/.test(value); – Dharmang Sep 10 '15 at 09:44
  • above regex is not working. use this instead: /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/ – Janos Szabo Jul 27 '17 at 14:35
  • lol. This has exactly the same problem as the OP: it allows emails without domain suffixes, ie. `myemail@something` is allowed – Inigo Oct 11 '19 at 16:36