Search code examples
asp.net-mvc-4remote-validation

Apply remote validation for hidden field in mvc4


The remote validation for the hidden field in mvc does not get fired Model :

[Remote("checker", "mycontroller", ErrorMessage = "Valid combination of phone and account number required.", HttpMethod = "Get")]
        public string Validate_cart { get; set; }

View :

@Html.HiddenFor(model => model.Validate_Paris)

Also tried setting value by using jquery :

$("#Phone_Number").blur(function () {
$("#Validate_cart").val = "dummy"
});

using jquery or by model the value is set but validations do not get fired. I checked using fiddler there is no call for the method being made anytime.

Method

 [HttpGet]
        public  bool checker(string Validate_cart )
        {
            try
            {

                bool isValid = //code to hit database to check the record
                return !isValid;               

            }
            catch (Exception)
            {
                throw;
            }
        }

Solution

  • hidden fields are ignored by jquery validation by default. this is due to the following setting.

    $("form").validate().settings.ignore
    

    this is set to ":hidden" so that validation ignores all hidden fields. What you can do is change the selector assigned in for ignore as follows.

    $(function(){
        $("form").validate().settings.ignore = ":hidden:not([id*=Validate_cart])";
    });
    

    Then it should fire the remote validation