using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
namespace MvcApp.Web.Classes
{
public sealed class PriceAttribute : ValidationAttribute, IClientValidatable
{
public double MinPrice { get; set; }
public double MaxPrice { get; set; }
public override bool IsValid(object value)
{
if (value == null)
{
return true;
}
var price = (double) value;
if (price < MinPrice || price > MaxPrice)
{
return false;
}
double cents = price - Math.Floor(price);
if (cents < 0.99 || cents >= 0.995)
{
return false;
}
return true;
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var rule = new ModelClientValidationRule
{
ErrorMessage = this.ErrorMessage,
ValidationType = "price"
};
rule.ValidationParameters.Add("min", this.MinPrice);
rule.ValidationParameters.Add("max", this.MaxPrice);
yield return rule;
}
}
}
2. 应用到实体
[Price(MinPrice = 3.99, MaxPrice = 9.99, ErrorMessage = "Price must end in .99 and be larger than 3.99 and less than 9.99")]
public double Price { get; set; }
3. 客户端定义注册
<script src="<%: Url.Content("~/Scripts/jquery.validate.min.js") %>" type="text/javascript"></script>
<script src="<%: Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js") %>" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$.validator.addMethod("priceMethod", function (value, element, params) {
if (this.optional(element)) {
return true;
}
//alert(value);
//alert(params);
//alert(params[0]);
var minValue = parseFloat(params[0]);
var maxValue = parseFloat(params[1]);
if (value > minValue && value < maxValue) {
var cents = value - Math.floor(value);
if (cents >= 0.99 && cents < 0.995) {
return true;
}
}
return false;
});
});
//$.validator.unobtrusive.adapters.addSingleVal("price", "min");
第一个参数是适配器的名称,必须与服务器端设置规则的ValidationProperty的值相同。第二个参数是用来检索元数据的参数名称。请注意,不需要在参数名中使用data-前缀;这里的参数需要与你在服务器端设置的ValidationParameters集合中的参数名相匹配。
$.validator.unobtrusive.adapters.addMinMax("price", "min", "max", "priceMethod");
</script>