-2

If my server side validation passes I want to show a message that I pass back from the server to the client. Error messages are possible (defined as an attribute on the property in ASP.Net MVC), can I show a success message? Maybe I can tap into the JQuery validate plugin to do this??

ex. I do a lookup from of the location to get a city I want to pass back the city as a string to display it as a validation success message.

Here is my code.

    [Required()]
    [MaxLength(5)]
    [MinLength(5, ErrorMessage = "Can't find location")]
    [Display(Name = "Zip code")]
    [Remote("CheckLocation", "Account", AreaReference.UseCurrent, ErrorMessage = "Invalid zipcode")]
    public string Location { get; set; }


    [HttpGet]
    [AllowAnonymous]
    public JsonResult CheckLocation(int Location)
    {
        var city = getLocation(Location);
        if (city != null)
        {
            // pass the city back with the JSon object, but how do I display it???
            return Json(true, JsonRequestBehavior.AllowGet);
        }
        return Json(false, JsonRequestBehavior.AllowGet);
    }

EDIT here is what I tried. I'm using jQuery Validate now instead of remote attributes on my c# property. This works fine but how do I define a success property here in remote and pass that success message to the validation messsage? and then change the color to green instead of red?

$('#Location').rules("add", {
  required: true,
  minlength: 5,
  maxlength: 5,
  messages: {
    required: "Required input",
    minlength: jQuery.validator.format("Please, {0} characters are necessary"),
    maxlength: jQuery.validator.format("Please, {0} characters are necessary")
  },
  remote: {
    url: "CheckLocation",
    type: "post",
    data: {
      Location: function() {
        return $('#Location').val();
      }
    }
  }
});

EDIT 2 I really want to show a succes message coming from the server (ex. shoing the city when a zip is entered), so I think I can use a success callback on the remote call and in the callback manipulate the message color and make the element valid. I think validate sets it to false if there is a string in the JSon response?

something like this.

        [HttpGet]
    [AllowAnonymous]
    public JsonResult CheckLocation(int Location)
    {
        var city = getLocation(Location);
        if (city != null)
        {
            return Json(city); // this will be text like "London"
        }
        return Json(false);
    }
$('#Location').rules("add", {
  required: true,
  //minlength: 5,
  maxlength: 5,
  messages: {
    required: "Required input",
    minlength: jQuery.validator.format("Please, {0} characters are necessary"),
    maxlength: jQuery.validator.format("Please, {0} characters are necessary")
  },
  remote: {
    url: "CheckLocation",
    type: "post",
    data: {
      Location: function() {
        return $('#Location').val();
      }
    },
    success: function(data) {
      // change the color from red to green for the message
      // make the invalid element valid so it passes submition
    }
  }
});
Sparky
  • 98,165
  • 25
  • 199
  • 285
chuckd
  • 13,460
  • 29
  • 152
  • 331
  • check this one it should help http://stackoverflow.com/questions/28366314/mvc5-data-annotations-client-side-validation-not-happening – mike123 Mar 09 '16 at 18:50
  • @user1186050 Why can you not use a label for the error or sucess message, give it an id and then set the value in the jquery depending on return value? – Mohit Shah Mar 09 '16 at 19:20
  • I guess I could, but isn't there some JQuery validate stuff going on under the hood? I want to show all the validate error messages. and I want to make sure the form has invalid fields before I try and submit – chuckd Mar 09 '16 at 19:30
  • what I'm basically trying to accomplish is to emulate www.okcupid.com register page where you enter in a zip and if the zip code is found is says "ah, San Francisco!" or "location not found" – chuckd Mar 09 '16 at 19:32
  • Using onfocusout event and Ajax will validate before you submit – Mohit Shah Mar 09 '16 at 19:34
  • If you feel my answer is correct please select it as answer and upvote – Mohit Shah Mar 09 '16 at 19:40
  • I think I might havea better solution. check my 2nd edit – chuckd Mar 09 '16 at 19:56
  • Please only use the "code snippet" feature for HTML/JavaScript/CSS code that can be run within the window on this page. Edited. Thanks. – Sparky Mar 09 '16 at 20:33

3 Answers3

1

The success option of the .validate() method is used for controlling the message element when validation passes. By default, the error message is hidden when validation passes. When using success, you can modify this behavior and show an icon, message, etc. when validation passes. However, this option does not retrieve messages from your server.

jQuery Validate is client-side code, and there is only one built-in method that will take a response from the server and that is the remote method. However, the issue here is that you can only pass a true to pass validation, a false to fail validation... and if you pass a string, it's converted into an error message and validation fails.

AFAIK, there is no built-in method for doing what you want. Perhaps you can write a custom success function that uses .ajax() to retrieve a message from your server.


Summary:

  1. the plugin does not typically show messages on success. The success option is a way to force it to show messages. However, the issue with this is that you cannot pass a value into this option. It's just a way to control the error message object when the field is valid.

  2. the plugin does not typically communicate with the server except for the remote method. The issue with this is that you can only pass true to pass validation. If you pass a string, validation will fail (and the string becomes the validation error message).


EDIT in response to OP:

but how do I define a success property here in remote and pass that success message to the validation messsage?

You can only use the success option to properly manipulate the error element. However, I don't think you'll be able to achieve the stated objective since there does not seem to be a way to pass the field's value into the success option. Otherwise, you could use .ajax() within success to retrieve your message.

and then change the color to green instead of red?

This is done automatically by defining your CSS properties for the valid and error classes. You can also apply custom classes using .addClass() within the success option.

IMO, your entire goal cannot be achieved using the jQuery Validate plugin. However, you should thoroughly review the documentation to be sure for yourself.


I think validate sets it to false if there is a string in the JSon response?

Yes, exactly as already stated in my answer. If the server response is anything other than true, the validation is set to fail.

Sparky
  • 98,165
  • 25
  • 199
  • 285
  • won't the remote call in validate take a success property that I can use to pass a message back to the client side? Then couldn't I just display it in the validation message and color it green or something? – chuckd Mar 09 '16 at 19:02
  • @user1186050 You said you wanted to display city – Mohit Shah Mar 09 '16 at 19:04
  • 1
    @user1186050, If the `remote` call gets *anything* other than `"true"`, the field is flagged as "invalid". – Sparky Mar 09 '16 at 19:05
  • what I want to show is the city, right. If I pass in a zipcode and a city is found I want to display the city in the validation message ex. "you found city San Francisco!", this would be after passing in "94102", other wise the error message is displayed saying something like "city not found" – chuckd Mar 09 '16 at 19:08
  • @user1186050 so did you try the method I told you it would exactly do what you want – Mohit Shah Mar 09 '16 at 19:10
  • 1
    @user1186050, as explained, 1. the plugin does not typically show messages on success. The `success` option is a way to force it to show messages. 2. the plugin does not typically communicate with the server except for the `remote` method. – Sparky Mar 09 '16 at 19:11
  • I'll post what I have above, butI'm not sure about the success message. – chuckd Mar 09 '16 at 19:11
0

What you can do is this

Use ajax to call a custom action method instead of remote data annotation

    var url = "/MyController/CheckLocation/";

$.ajax({
    url: url,
    data: { zipcode: _zipcode },
    cache: false,
    type: "POST",
    dataType: "json"
}).done(function (obgcity) {

     //If objcity is null then display error else display city
    }
});
Mohit Shah
  • 843
  • 1
  • 6
  • 20
0

I wish code below helps you.

public ActionResult CheckLocation(int Location)
    {
        var city = getLocation(Location);
        if (city != null)
        {
            // city is string type, example: string city="Mumbai";
            return Json(new {Status=true, City = city}, JsonRequestBehavior.AllowGet);
        }
        return Json(new { Status=false, City=""}, JsonRequestBehavior.AllowGet);
    }

Now as Sparky has mentioned in message above give call to your action or method using ajax and write a custom success function

 var locationId = 20;
 $.ajax({
    url: "MyController/CheckLocation",
    data: { Location: locationId},
    cache: false,
    type: "GET",
    dataType: "json",
    success: function (data) {
             if(data.Status == true)
             {
                 alert(data.City); 
                // instead of alert you can create custom message alert box,
                // or if you want to display city name or whatever message
                // you can try $("#cityId").Html("<p>this is city</p>");   
             }        
    },
    error: function (xhr, ajaxOptions, thrownError) {
        alert("Ajax Failed!!!");
     }
});
rishi
  • 359
  • 2
  • 6