Creating a custom validation through DataAnnotations?

后端 未结 2 1708
一整个雨季
一整个雨季 2021-01-22 14:19

Ok so when I want to have a property be validated, I might write something like this:

    [Required]
    [StringLength(255)]
    [DataType(DataType.EmailAddress)         


        
相关标签:
2条回答
  • 2021-01-22 14:38

    This SO answer givens an answer for MVC2.

    And here is a post for MVC3 and up.

    Basically you create an Attribute:

    public class MyValidationAttribute: ValidationAttribute
    {
       public MyValidationAttribute()
       { }
    
        protected override ValidationResult IsValid(
               object value, ValidationContext validationContext)
        {
    
            ...
            if (somethingWrong)
            {
                return new ValidationResult(errorMessage); 
            }
            return null; // everything OK
        }
    }
    
    0 讨论(0)
  • 2021-01-22 14:48

    The documentation for ValidationAttribute shows how to create your custom validation attribute.

    0 讨论(0)
提交回复
热议问题