1
如何在客户端触发自定义验证器? 这是我到现在为止:自定义属性的ASP.NET MVC客户端验证
我的验证类:从Metdata类
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;
}
}
代码:
[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行
请看看: http://stackoverflow.com/questions/4747184/perform-client-side-validation-for-custom-attribute/4747466 – 2014-09-10 09:43:55
的联系是这个职位。 – POIR 2014-09-10 09:45:55
对不起,更新了正确的URL – 2014-09-10 09:48:29