[MetadataType(typeof(TB_Product_Validation))]
public partial class TB_Product
{
}
public class TB_Product_Validation
{
/// <summary>
/// code产品编码 验证
/// </summary>
[Required(ErrorMessage = "*不能为空")]
[StringLength(10, ErrorMessage = "*不能超过10个字符")]
public String Code { get; set; }
/// <summary>
/// 产品名称 验证
/// </summary>
[Required(ErrorMessage = "*")]
[RegularExpression("/w{2,5}")]
public string Name { get; set; }
/// <summary>
///
/// </summary>
[Required(ErrorMessage = "*")]
[Remote("Private_Validation","home")]
public decimal Price { get; set; }
[Required(ErrorMessage = "*")]
public string ModelName { get; set; }
[Required(ErrorMessage = "*")]
[RegularExpression("/d{1,10")]
public long SortID { get; set; }
如何自己写验证呢?
如我想让Price属性在一个范围之间,或者小于另一个参数的数据,谢谢啊!
好像有一个CompareAttribute吧
1)类似price这样的,在一个范围之内的,可以用以下代码:
[Range(0, 9999)]
public object Price{ get; set; }
如果想自定义验证规则的话, 你就继承ValidationAttribute.
谢谢~~~
我有一个CompareAttribute,比MVC 内置的CompareAttribute功能要强,可以实现日期、整型、浮点数、字符串的的>、<、>=、<=、==的比较.
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Web.Mvc;
using Xoohoo.Extensions;
using Xoohoo.Validation.ModelClientValidationRules;
namespace Xoohoo.Validation.Attributes
{
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = true, Inherited = true)]
public class CompareAttribute : ValidationAttribute, IClientValidatable
{
public string OtherProperty { get; private set; }
public object ValueToCompare { get; private set; }
public ValidationCompareOperator Operator { get; private set; }
public ValidationDataType DataType { get; private set; }
private const string _defaultErrorMessage = "对{0}和{1}属性或值进行{2}型的{3}比较失败";
public CompareAttribute(string originalProperty, ValidationCompareOperator compareOperator, ValidationDataType dataType)
: this(originalProperty,null,compareOperator,dataType)
{
}
public CompareAttribute(string originalProperty, object valueToCompare, ValidationCompareOperator compareOperator, ValidationDataType dataType)
: base(_defaultErrorMessage)
{
OtherProperty = originalProperty;
ValueToCompare = valueToCompare;
Operator = compareOperator;
DataType = dataType;
}
public override string FormatErrorMessage(string name)
{
return String.Format(CultureInfo.CurrentUICulture, ErrorMessageString,
name, OtherProperty,DataType.ToString(), Operator.ToString());
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
ValidationResult validationResult = null;
if (!String.IsNullOrEmpty(OtherProperty))
{
PropertyInfo originalProperty = validationContext.ObjectType.GetProperty(this.OtherProperty);
object otherValue = originalProperty.GetValue(validationContext.ObjectInstance, null);
if (!Compare(this.Operator, this.DataType, value, otherValue))
validationResult = new ValidationResult(this.FormatErrorMessage(validationContext.DisplayName));
}
if (validationResult==null&&ValueToCompare!=null&&!Compare(this.Operator, this.DataType, value, ValueToCompare))
validationResult = new ValidationResult(this.FormatErrorMessage(validationContext.DisplayName));
if (validationResult != null)
return validationResult;
return ValidationResult.Success;
}
private static bool Compare(ValidationCompareOperator compareOperator, ValidationDataType dataType, object value, object otherValue)
{
int num = 0;
try
{
switch (dataType)
{
case ValidationDataType.String:
num = string.Compare(value != null ? value.ToString() : String.Empty, otherValue!=null?otherValue.ToString():String.Empty, false, CultureInfo.CurrentCulture);
break;
case ValidationDataType.Integer:
num = ((int)value).CompareTo(otherValue);
break;
case ValidationDataType.Double:
num = ((double)value).CompareTo(otherValue);
break;
case ValidationDataType.Date:
num = ((DateTime)value).CompareTo(otherValue);
break;
case ValidationDataType.Currency:
num = ((decimal)value).CompareTo(otherValue);
break;
}
}
catch {
return false;
}
switch (compareOperator)
{
case ValidationCompareOperator.Equal:
return (num == 0);
case ValidationCompareOperator.NotEqual:
return (num != 0);
case ValidationCompareOperator.GreaterThan:
return (num > 0);
case ValidationCompareOperator.GreaterThanEqual:
return (num >= 0);
case ValidationCompareOperator.LessThan:
return (num < 0);
case ValidationCompareOperator.LessThanEqual:
return (num <= 0);
}
return true;
}
public static string FormatPropertyForClientValidation(string property)
{
if (String.IsNullOrEmpty(property))
{
throw new ArgumentNullException("property");
}
return ("*." + property);
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
return new ModelClientValidationRule[]{
new ModelClientValidationCompareRule(FormatErrorMessage(metadata.GetDisplayName())
, !String.IsNullOrEmpty(OtherProperty)?FormatPropertyForClientValidation(OtherProperty):null
, ValueToCompare.ToNullableString()
, DataType.ToString()
, Operator.ToString()
)
};
}
}
}