0

Regarding the jQuery .validate plugin, I want to add/edit/replace to the email method to accommodate two extra rules/conditions.

The email method (which can be tested here: https://jqueryvalidation.org/email-method/) allows the following to pass but I want them to fail:

  • test.@test.com
  • test@test

How can I achieve this?

Warren
  • 1,984
  • 3
  • 29
  • 60
  • Over ride it as in the docs example https://jqueryvalidation.org/jQuery.validator.methods/ – charlietfl Oct 18 '17 at 22:58
  • Or create your own with custom name using `$.validator.addMethod()` – charlietfl Oct 18 '17 at 22:59
  • I've found the "email" rule, so now I'm stuck with the right regex. The "email" rule is /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/ – Warren Oct 18 '17 at 23:00
  • Actually, that email rule is terrible - it allows all sorts of non-email characters! – Warren Oct 18 '17 at 23:04
  • Lots of regex to be found online for email. Find one you like and use it in over ride – charlietfl Oct 18 '17 at 23:05
  • FYI: The existing `email` rule simply follows the HTML5 standard for valid email addresses. – Sparky Oct 19 '17 at 00:50

1 Answers1

0

As @charlietfl said, override it.

My new method is:

$.validator.addMethod('betterEmail', function (value, element) {
            return this.optional(element) || /^(([^<>()\[\]\\.,;:\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,}))$/.test(value);
        }, "Please enter a valid email address.");

And my rules now look like this:

rules: {
         email:      {betterEmail: true}
       }
Warren
  • 1,984
  • 3
  • 29
  • 60