Jquery validation – addMethod/remote – error message in json response

jqueryjquery-validatejson

I'm trying to either use the remote method, or add a method that mimics the remote method to be able to send the entered data to a web service and get a json response back with the error state and error message.

so I have this json response:

{
    "isError": "true",
    "errorMessage": "The User Name you chose is already in use. Please enter another name."
}

I've used the remote method to get a true/false response, but not with extra data.

Any help would be appreciated.

Edit

Tried this, but of course it didn't work because the variable is not a global variable…

$.validator.addMethod("uniqueUserName", function(value, element) {

      $.ajax({
        type: "POST",
         url: "js/username.json",
         contentType: "application/json; charset=utf-8",  
        dataType:"json",
        data: "{'" + $('#enterEmail').attr('id') + "': '" + $('#enterEmail').val() + "'}", 
        dataFilter: function(data) {
            var isError = data.isError;
            var uniqueError = data.errorMessage;
            if(isError == "true"){
                return false;
            }
        }

     })

}, uniqueError); //this last line would typically be: }, "my error message");

see fiddle:
http://jsfiddle.net/jasonday/fWk5u/

Best Answer

I ended up figuring it out. The return success is what I was failing - I kept returning, returning true, or returning false - and every one of them would "fail" validation.

remote: {
    type: "POST",
    url: "js/username.json",
    contentType: "application/json; charset=utf-8",  
    dataType:"json",
    data: "{'" + $('#enterEmail').attr('id') + "': '" + $('#enterEmail').val() + "'}",
    dataFilter: function(data) {
        var json = JSON.parse(data);
        if(json.isError == "true") {
            return "\"" + json.errorMessage + "\"";
        } else {
            return success;
        }

    }
}
Related Topic