0
votes

I am trying to use jQuery validation to validate an email input field against our database, to see if the email ID already exists.

The input field looks like this.

<input name='email' id='id_email'/>

The validation is done like this. I'm binding the remote rule later.

var validator = $('form').validate({
       rules: { "email": {required:true,email:true} },
       messages: { "email": {
          required:'Please enter your email ID.',
          email:'Please enter a valid email ID.',
          remote: $.format('{0}')
        }}
});

$('#id_email').rules('add', {
       remote:{
          url:'/validate/',
          type:'post',
          dataType:'text',
          data:{'id_email':function() { return $('#id_email').val(); }}
       }
});

Now the server would respond with the error message (some plain text) if validation failed, or nothing if validation passes through.

I'm able to display the error message from the server correctly when validation fails. However, when a valid email ID is entered and the server responds with an empty response, the error message shows the input field's value. How do I treat this as true validation and not display any error message?

1
why don't you just return 'true' from the server? This is what the plugin expects so you won't need to do anything special - Dr Blowhard
This might break a bunch of other stuff, as there are cases for validation (of other fields) where we return different responses for a single field. - GPX

1 Answers

0
votes

Unfortunately that's the way the remote method works with this plugin. If you return true from the server, the element is valid... if the server returns false, null, or undefined, the element displays the message and the element is considered invalid.

"...must be true for valid elements, and can be any false, undefined or null for invalid elements"

Perhaps you can write your own custom remote method... just make sure the method returns true for your particular response.

jQuery.validator.addMethod("customRemote", function(value, element, params) {
    // your ajax;
    // if server response is something good, then return true
    // if server response is not so good, then return false and error message displays
}, "This is the error message");

See: http://jqueryvalidation.org/jQuery.validator.addMethod/