1

I am trying to use jQuery validation remote method to check if a value is unique The rule is added on submit to prevent it from being fired on every keystroke

var Id = $("#id").val();

$('#form').on('submit', function (e) {
    e.preventDefault();
    var newValue = $('#input').val();

$('#input').rules('add', {
    'remote': {
        url: '/MyController/CheckValue',
        type: 'POST',
        data: {
            id: Id,
            value: newValue
        }
    },
    messages: {
        'remote': 'This value is not valid'
    }
});

if ($('#form').valid()) {
    window.console.log('valid')
    // do something
}

$('#input').rules('remove', 'remote');
});

The action returns true or false after a call to a service

[HttpPost]
public JsonResult CheckValue(int? id, string value)
{
    bool available;
    using (var myServiceClient = new MyServiceClient())
    {
        available = myServiceClient.IsValueAvailable(id, value);
    }
    return this.Json(available);
}

The rule works fine, but the $('#form').valid() returns true everytime because it is not waiting for the remote rule to finish it's call.

This post suggests to use async: false in the remote rule declaration but this freezes the browser. The examples in the documentation are not using this, so it should be working without it.

Is there something wrong with my validation rule ?

Community
  • 1
  • 1

1 Answers1

0

According to the documentation you should be attaching the rules and validation method directly to the form and using a submitHandler callback like so:

$('#form').validate({
    rules: {
        inputName: {
          remote: {
            url: '/MyController/CheckValue',
            type: 'POST',
            data: {
                id: Id,
                value: newValue
            }
        }
    },
    messages: {
        inputName: {
            remote: 'This value is not valid'
        }
    },
    submitHandler: function(form){
        // Do Stuff with Form
    }
}

I hope this helps!

dSquared
  • 9,725
  • 5
  • 38
  • 54
  • Close... the method is called `.validate()` not `.validation()`. – Sparky May 28 '13 at 17:07
  • Thanks for the answer, but I forgot to mention i was using jQuery validation combined with MVC unobtrusive validation, so this step is already done by this plugin, and the unobtrusive validation works fine. I just want to add a new rule to the existing validation on the form, it works well with classic rules, but not with remote rules : the form is validated before the result of the remote validation. – Lucien Clement May 29 '13 at 07:08