【发布时间】:2014-11-03 21:40:17
【问题描述】:
如何在客户端触发自定义验证器? 这是我到目前为止所拥有的:
我的验证类:
public class AlmostEqual : ValidationAttribute, IClientValidatable
{
private readonly string _otherProperty;
private readonly float _myPercent;
public AlmostEqual(string otherProperty,float percent)
{
_otherProperty = otherProperty;
_myPercent = percent;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var property = validationContext.ObjectType.GetProperty(_otherProperty);
var otherPropertyValue = property.GetValue(validationContext.ObjectInstance, null);
dbEntities db = new dbEntities();
Metal metal = db.Metals.Find(Convert.ToInt32(otherPropertyValue));
double _unitWeight = metal.UnitWeight;
double _percent = metal.UnitWeight * (_myPercent / 100);
double myProperty = double.Parse(value.ToString());
bool result = myProperty >= _unitWeight - _percent && myProperty <= _unitWeight + _percent;
if (!result)
{
return new ValidationResult(string.Format(
CultureInfo.CurrentCulture,
FormatErrorMessage(validationContext.DisplayName),
new[] { _otherProperty }
));
}
return null;
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var rule = new ModelClientValidationRule
{
ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()),
ValidationType = "almostequal",
};
rule.ValidationParameters.Add("other", _otherProperty);
yield return rule;
}
}
来自 Metadata 类的代码:
[Required]
[AlmostEqual("IDMetal",5,ErrorMessage="Weight do not correspond with dimensions.")]
public Nullable<double> UnitWeight { get; set; }
}
鉴于我添加了这个js:
<script type="text/javascript">
$.validator.unobtrusive.adapters.addBool("almostequal", "Range");
</script>
我的 webconfig 包含:
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
我得到错误:
未捕获的类型错误:无法读取文件中未定义的属性“调用” jquery.validate.min.js 在第 27 行
【问题讨论】:
-
链接来自这篇文章。
-
抱歉,更新了正确的网址
-
但是我不明白为什么当我们有一个类来进行验证时我们应该创建一个 javascript 函数。
-
这就是原因,客户端JavaScript函数被称为适配器。它可以将您的服务器验证内容转换为客户端。不幸的是,没有直接的方法可以将您的服务器行为转换为客户端。
标签: c# jquery asp.net-mvc validation