JQuery Validate Plugin: test value for email template?

I use the jQuery Validate plugin for all my forms on my site.

Like for example:

$("#accountUserSettingsForm").validate({ rules: { 'user[email]': { required: true, email: true } }, messages: { 'user[email]': { required: "*", email: "No valid email address." } }, submitHandler: function() { // do something } }); 

This works great. Now I am wondering if it is also possible to check a simple $ ('# selector') for a valid email address, and if you do something. So, without any form?

eg. I have an input with the identifier #email , and now I enter the keystroke function when I run the function whenever a key is entered inside this input.

Is it possible to simply check this #email field for a valid email and do something? Sort of...

 if ( $('#email').validate(rules:email) ) { is_email = true; } 

maybe with this plugin?

Thank you in advance!

+4
source share
1 answer

Not so simple, but it can be done with:

 $.validator.methods.email.call( {optional:function(){return false}}, $('#email').val(), $('#email')); 

This call will return true if it is a valid email address.

Brief explanation:

First line: you can call the authentication method for email directly

Second line: you must provide a method that returns false, which indicates that this field is not optional.

Third line: indicate the actual value

Forth Line: Provide the item, it really is not necessary, you could not provide anything, and it will work. The email authentication module accepts this element to check if it is optical. But since we provide a false value regardless of the argument we receive, it does not matter.

To make things a little easier, you can wrap this in your own plugin:

 (function($){ $.fn.validate_email = function(){ var text = this.first().text(); return $.validator.methods.email.call( {optional:function(){return false}}, text, this); }; })(jQuery); 

and name it $('#email').validate_email()

+5
source

Source: https://habr.com/ru/post/1379807/


All Articles