简体   繁体   中英

ASP.NET 4.5 Custom Validation Attribute. IsValid() called too late

I am kind of a newbie in the ASP.NET world. I want to create a custom validation for a property of a viewModel class. Let's say that this validation checks if the input is an integer greater than 10. So in the MyViewModel.cs file we have the following code parts:

[GreaterThanTen]
[RegularExpression("^[0-9][0-9]*$", ErrorMessageResourceType = typeof(Resources.Resource),
        ErrorMessageResourceName = "NonNegativeIntMessage")]
[Required(ErrorMessageResourceType = typeof(Resources.Resource),
        ErrorMessageResourceName = "RequiredValidationMessage")]
[UIHint("OwTextbox")]
public int MyInt { get; set; }

is the definition of the aforementioned property and:

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public class GreaterThanTenAttribute : ValidationAttribute
{
    public GreaterThanTenAttribute() : base(Resources.Resource.GreaterThanTen) { }

    protected override ValidationResult IsValid(Object value,ValidationContext validationContext)
    {
        if (value != null)
        {
            if (value is int) // check if it is a valid integer
            {
                int suppliedValue = (int)value;
                if (suppliedValue > 10)
                {
                    return ValidationResult.Success;

                }
            }

        }

        return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
    }

}

is the extended ValidationAttribute class used to define the validation message.

Then there is a webpage which inludes this form:

<form name="my-form" id="my-form">
  <div class="form-group">
     <label for="MyObject_MyInt">My points:</label>
     <div class="form-group-inner">
         <div class="field-outer">
            @Html.TextBoxFor(m => m.MyObject.MyInt, new { @class = "input-lg"})
            @Html.ValidationMessageFor(m => m.MyObject.MyInt)
         </div>
      </div>
   </div>
</form>

And when a button is clicked the following javascript function is called in order to validate the TextBox value and insert it into the database...

function insertData() {
   if ($("#my-form").valid()) {
     ...
   }
}

The problem is that all standard validations such as the Regular Expression defining that the value should be a non-negative integer are performed when execution reaches the if ($("#my-form").valid()) except for the custom IsGreaterThanTen validation which is called later on (not sure what triggers it) after the field has been validated and the value has been processed. What am I doing wrong?

Your custom validator is implemented in c# and is living "server-side". It doesn't have any corresponding client side javascript implementation so what actually happens is your form is posted back to the controller where your validator is ran, model validation fails and it posts back to the page with validation errors to be displayed.

What you have to do is on the server side, in your controller httpPost handler check if validation has been successful prior to processing the viewModel eg :

if(ModelState.IsValid){
 PerformProcessingOf(viewModel);
 //Redirect or whatever...
}
else
return view(viewModel);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM