1、自带验证
[Require]
//长度6-100
[StringLength(100, MinimumLength = 6)]
[DataType(DataType.Password)]
[RegularExpression(@"[A-Za-z0-9._%+-]+@[A-Za-z0-9._]+\.[A-Za-z]{2,4}")]
public string Password { get; set; }
[Compare("Password", ErrorMessage = "密码和确认密码不匹配。")]
public string ConfirmPassword { get; set; }
[Range(13, 18)]
//Model
[Required]
[Display(Name = "用户名")]
[Remote("CheckUserName","Account")]
public string UserName { get; set; }
//control
public JsonResult CheckUserName(string userName)
{
var result = userName == "admin";
return Json(result, JsonRequestBehavior.AllowGet);
}
2、自定义验证
2.1 继承ValidationAttribute(全局都可以使用)
public class MyMaxLengthAttribute : ValidationAttribute
{
private readonly int MaxLength;
public MyMaxLengthAttribute(int maxLength)
{
MaxLength = maxLength;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
string content = value.ToString();
if (content.Length > MaxLength)
{
return new ValidationResult("输入的字符太多了!^_^");
}
return ValidationResult.Success;
//return base.IsValid(value, validationContext);
}
2.2 Model类实现接口IValidatableObject(限于该Model类使用,但可以很方便地对该Model的所以属性进行验证)
public IEnumerable<ValidationResult> Validate(ValidationContext validationContent)
{
if (Password != ConfirmPassword)
{
yield return new ValidationResult("两次输入的密码不同!", new[] { "Password" });
}
}
网友评论