Sam*_*mWM 42 asp.net data-annotations asp.net-mvc-2
想要创建自定义数据注释验证.有关如何创建它们的有用指南/示例吗?
首先:
具有最小和最大长度的StringLength.我知道.NET 4可以做到这一点,但是想在.NET 3.5中做同样的事情,如果可能的话,只能定义最小长度(至少x个字符),最大长度(最多x个字符),或者两者都是(在x和y之间).
其次:
使用模数运算验证 - 如果数字是有效长度,我希望使用模数11算法进行验证(我已经在JavaScript中实现了它,所以我想它只是一个简单的移植?)
更新:
解决了第二个问题,只是复制JavaScript实现并进行一些调整,所以不需要解决方案.
Rob*_*nik 89
要创建自定义数据注释验证器,请遵循以下指南:
System.ComponentModel.DataAnnotations.ValidationAttribute班级继承.bool IsValid(object value)方法并在其中实现验证逻辑.而已.
有时开发人员检查该值是否为null/empty并返回false.这通常是不正确的行为,因为在Required验证器上检查哪个意味着您的自定义验证器应该只验证非空数据,true否则返回(参见示例).这将使它们可用于强制(必需)和非强制字段.
public class StringLengthRangeAttribute : ValidationAttribute
{
public int Minimum { get; set; }
public int Maximum { get; set; }
public StringLengthRangeAttribute()
{
this.Minimum = 0;
this.Maximum = int.MaxValue;
}
public override bool IsValid(object value)
{
string strValue = value as string;
if (!string.IsNullOrEmpty(strValue))
{
int len = strValue.Length;
return len >= this.Minimum && len <= this.Maximum;
}
return true;
}
}
Run Code Online (Sandbox Code Playgroud)
您可以根据需要设置属性中的所有属性.
一些例子:
[Required]
[StringLengthRange(Minimum = 10, ErrorMessage = "Must be >10 characters.")]
[StringLengthRange(Maximum = 20)]
[Required]
[StringLengthRange(Minimum = 10, Maximum = 20)]
Run Code Online (Sandbox Code Playgroud)
如果未设置特定属性,则在构造函数中设置其值,因此它始终具有值.在上面的用法示例中,我还故意添加了Required验证器,因此它与我编写的上述警告同步.
因此,此验证器仍然可以处理您不需要的模型值,但是当它存在时,它会验证(想想Web表单中的文本字段,这不是必需的,但如果用户输入值,则必须有效) .
使用CustomValidationAttribute与签名验证功能一起
public static ValidationResult Validate(MyType x, ValidationContext context)
Run Code Online (Sandbox Code Playgroud)
示例(用于字符串属性)
using System.ComponentModel.DataAnnotations;
public class MyClass
{
[CustomValidation(typeof(MyClass), "Validate")]
public string MyProperty { get; set; }
public static ValidationResult Validate(string x, ValidationContext context)
{
return (x == "valid")
? new ValidationResult(null)
: ValidationResult.Success;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
53290 次 |
| 最近记录: |