MVC 验证和异常处理 自动验证使用Data Annotations Validation Attributes

    使用数据标签验证属性,control不用劳什子一一手工指定验证,在model binding期间,所有标记属性会自动启用验证,并把不合法信息登记进ModelState。View不需要任何变化。默认,asp.net mvc注册使用DataAnnotationsModelValidationFactory,它能识别的标签包括:[Range],[RegularExpression],[Required],[StringLength]。

示例:

public class Appointment

{

    [Required(ErrorMessage = "Please enter your name")] [StringLength(50)]

    public string ClientName { get; set; }

    [DataType(DataType.Date)] [Required(ErrorMessage = "Please choose a date")]

    public DateTime AppointmentDate { get; set; }

}

可以创建自己的Data Annotations Validation Attribute

public class ValidEmailAddressAttribute : ValidationAttribute

{

    public ValidEmailAddressAttribute()

    {

        // Default message unless declared on the attribute

        ErrorMessage = "{0} must be a valid email address.";

    }

    public override bool IsValid(object value)

    {

        // You might want to enhance this logic...

        string stringValue = value as string;

        if (stringValue != null)

            return stringValue.Contains("@");

        return true;

    }

}

public class Appointment

{

    [Required(ErrorMessage = "Please enter your name")] [StringLength(50)]

    public string ClientName { get; set; }

    [DataType(DataType.Date)] [Required(ErrorMessage = "Please choose a date")]

    public DateTime AppointmentDate { get; set; }

    [ValidEmailAddress]

    public String Email { get; set; }

}

你可能感兴趣的:(Annotations)