【发布时间】:2016-11-30 09:57:36
【问题描述】:
我是 ASP.NET 领域的新手。我想为 viewModel 类的属性创建自定义验证。假设此验证检查输入是否为大于 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; }
是上述属性的定义,并且:
[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));
}
}
是用于定义验证消息的扩展 ValidationAttribute 类。
然后有一个网页包含这个表格:
<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>
当单击按钮时,会调用以下 javascript 函数以验证 TextBox 值并将其插入数据库...
function insertData() {
if ($("#my-form").valid()) {
...
}
}
问题是当执行到达if ($("#my-form").valid()) 时执行所有标准验证,例如定义值应该是非负整数的正则表达式,除了自定义 IsGreaterThanTen 验证之外在验证字段并处理值后稍后调用(不确定是什么触发它)。我做错了什么?
【问题讨论】:
标签: javascript c# jquery asp.net validation