Reputation: 44293
i'm using the jQuery Validate Plugin on all my forms on my site.
Like e.g. so:
$("#accountUserSettingsForm").validate({
rules: {
'user[email]': {
required: true,
email: true
}
},
messages: {
'user[email]': {
required: "*",
email: "No valid email address."
}
},
submitHandler: function() {
// do something
}
});
This works just fine. Now I wonder if it's also possible to test a simple $('#selector') for a valid email address and if so do something. So without having any form at all?
E.g. I have an input with an id of #email
and i'm currently in an keypress function where I fire functions whenever a key inside of that input is typed.
Is it simply possible to test this #email field for a valid email and do something? Something like …
if ( $('#email').validate(rules:email) ) {
is_email = true;
}
is that possible with that plugin?
thank you in advance!
Upvotes: 4
Views: 1933
Reputation: 18979
Not quite that 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
Short explanation:
First line: You can call the validator method for email directly
Second Line: You have to provide a method that returns false, which indicates that this field is not optional.
Third line: Provide the actual value
Forth Line: Provude the element, this is not really necessary you could provide nothing and it would work. The email validator takes this element to check, whether it's optinal. But as we provide a false regardless of the argument we get, this does not matter
To make things a bit simpler you could 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 call it with $('#email').validate_email()
Upvotes: 5