0

I have a custom message which is the return type of the remote validation method, when the return type was Boolean it was working fine, but now when I changed the return type then I'am getting input-validation-error class in the input field but no error message is displayed.(I have error messages written). i don't know what is causing to add that class in the input field.

Remote Validation

[Remote("Checkmail", "api", ErrorMessage = "Already taken")]
        public string Email { get; set; }

Method that is being called

public Message Checkmail(string email)
        {
            try
            {

                if(email=="test@test.com")
                   {
                       return new Message{MessageCode = "True"}; 
                   }
             return new Message{MessageCode= "false"};
            }
            catch (Exception)
            {
                throw;
            }
        }

AJAX call

 $(document).ajaxComplete(function (event, xhr, settings) {

            var status = xhr.responseJSON;
                if (status.MessageCode == "True") {
                   //CSS to change 
                }
Nikitesh
  • 1,287
  • 1
  • 17
  • 38

1 Answers1

2

Please, read this article, that gives a full explanation of how remote validation works. Pay special attention to this lines:

Any response other than true is considered false

So if your JSON is different from true, it's regarded as being an error. And, if is an string, it will be shown as the error message on the clien side.

So, your remote valdiation action should return:

  • either true, if it's correct
  • or an string with the error message, which will be shown in the browser

If you return anything else, it will be regarded as error, but the message will be lost. If you wnat a fixed error message, return that string from the validation action in your controller.

So your action must return a JsonResult, you can return what you need:

if (valid)
{
  return Json(true); 
}
else
{
  return Json("this is the error message");
}
JotaBe
  • 38,030
  • 8
  • 98
  • 117
  • so is there any work around for passing the string and still getting the true reply. – Nikitesh Jan 15 '14 at 13:58
  • Why do you need to pass a string if the validation result is true? Let me know the reason, and perhaps I can help you. – JotaBe Jan 15 '14 at 14:35
  • its for further purpose i need to pass the entity as response which is used further. that is why the response type can't be just true or false – Nikitesh Jan 16 '14 at 13:03
  • You cannot do it directly. The attribute based validation requires this pattern. You can only solve your problem by making a custom validator: http://bradwilson.typepad.com/blog/2010/10/mvc3-unobtrusive-validation.html – JotaBe Jan 17 '14 at 09:26