Jquery check remote rule and depends on input value change
I'm using the jQuery validation plugin and came up with the script I need to create a remote validation rule.
Let's say I had a members form that users can edit their profile containing their email address and other information that is populated from a database. Obviously I would test using a remote method to check that the emails do not already exist when they are registered. The problem is that the user doesn't want to update their email address, but when the form is saved, the validation will make a fuss, saying that the email already exists.
Is it possible to use the remote method ONLY if the email has been changed on the form. If the letter remains intact, there is no need to check.
Here's an example of a remote method that works for something else:
rules: {
something: {
required: true,
remote: {
param: {
url: '/path/to/file.php',
type: 'post',
data: {
'test': $('#something').val()
}
},
depends: function() {
return $('body').hasClass('someClass');
}
}
}
I would have thought I could put some check on the dependent part of the rule that checks the change, but I don't know how
source to share
-
Add a hidden field to your form and set it
value
to the original email address from the database on page load. Also give itid
to him for later reference. (Note that the jQuery Validate plugin ignores all hidden fields by default. It will not be validated, so it doesn't need an attributename
.)<input type="hidden" value="foo@bar.com" id="originalemail" />
Entering the text of your email address ...
<input type="text" value="foo@bar.com" name="emailaddress" />
-
Compare the
value
hidden field with thevalue
fieldemail
independs
your rule optionremote
.rules: { emailaddress: { // <- assumes 'name' of field is 'emailaddress' required: true, email: true, // <- make sure data is a valid email address remote: { param: { url: '/path/to/file.php', type: 'post', //data: // < do not need. Value of 'emailaddress' is sent by default. }, depends: function(element) { // compare email address in form to hidden field return ($(element).val() !== $('#originalemail').val()); } } // close remote } // close emailaddress } // close rules
Note that the argument
element
passed to the functiondepends
represents a fieldemailaddress
.
source to share