简体   繁体   English

ASP.NET 4.5自定义验证属性。 IsValid()调用为时已晚

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

I am kind of a newbie in the ASP.NET world. 我是ASP.NET世界中的新手。 I want to create a custom validation for a property of a viewModel class. 我想为viewModel类的属性创建自定义验证。 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: 假设此验证检查输入是否为大于10的整数。因此,在MyViewModel.cs文件中,我们具有以下代码部分:

[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. 是用于定义验证消息的扩展ValidationAttribute类。

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... 当单击按钮时,将调用以下javascript函数,以验证TextBox值并将其插入数据库中...

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. 问题是,除了自定义IsGreaterThanTen以外,所有标准验证(例如正则表达式均定义该值应为非负整数)均在执行达到if ($("#my-form").valid())时执行if ($("#my-form").valid())验证,该验证在字段已验证并且值已处理后,稍后调用(不确定触发它的原因)。 What am I doing wrong? 我究竟做错了什么?

Your custom validator is implemented in c# and is living "server-side". 您的自定义验证器是用c#实现的,位于“服务器端”。 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. 它没有任何相应的客户端javascript实现,因此实际发生的情况是将您的表单回发到运行验证器的控制器上,模型验证失败,并且回发到要显示验证错误的页面。

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 : 您需要做的是在服务器端,在控制器的httpPost处理程序中,在处理viewModel之前检查验证是否成功,例如:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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