首页 新闻 会员 周边 捐助

MVC 3.0验证问题,用的是自带的验证,我想扩展,谢谢

0
悬赏园豆:40 [待解决问题]

 [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属性在一个范围之间,或者小于另一个参数的数据,谢谢啊!

IT学者的主页 IT学者 | 初学一级 | 园豆:65
提问于:2011-05-05 18:00
< >
分享
所有回答(3)
0

好像有一个CompareAttribute吧

阿不 | 园豆:665 (小虾三级) | 2011-05-05 20:12
0

1)类似price这样的,在一个范围之内的,可以用以下代码:

[Range(0, 9999)]
public object Price{ get; set; }

如果想自定义验证规则的话, 你就继承ValidationAttribute.

谢谢~~~
 

DYStudio.Net | 园豆:1747 (小虾三级) | 2011-05-05 21:06
呵呵,能给个例子吗?非常感谢
支持(0) 反对(0) IT学者 | 园豆:65 (初学一级) | 2011-05-06 09:03
例子:
http://tech.ddvip.com/2010-01/1263285858143083.html
支持(0) 反对(0) DYStudio.Net | 园豆:1747 (小虾三级) | 2011-05-15 22:16
0

我有一个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()
)
};
}
}
}

alby | 园豆:323 (菜鸟二级) | 2011-05-18 18:01
namespace Xoohoo.Validation.Attributes
{
public enum ValidationCompareOperator : byte
{
Equal, NotEqual,GreaterThan,GreaterThanEqual,LessThan,LessThanEqual
}
}
支持(0) 反对(0) alby | 园豆:323 (菜鸟二级) | 2011-05-18 18:02
namespace Xoohoo.Validation.Attributes
{
public enum ValidationDataType : byte
{
String,
Integer,
Double,
Date,
Currency, /*Decimal*/
}

}
支持(0) 反对(0) alby | 园豆:323 (菜鸟二级) | 2011-05-18 18:02
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册