ASP.NET Core - Custom model validation

前端 未结 2 1697
滥情空心
滥情空心 2021-02-07 02:07

In MVC when we post a model to an action we do the following in order to validate the model against the data annotation of that model:

if (ModelState.IsValid)
         


        
2条回答
  •  深忆病人
    2021-02-07 02:49

    In .NET Core, you can simply create a class that inherits from ValidationAttribute. You can see the full details in the ASP.NET Core MVC Docs.

    Here's the example taken straight from the docs:

    public class ClassicMovieAttribute : ValidationAttribute
    {
        private int _year;
    
        public ClassicMovieAttribute(int Year)
        {
            _year = Year;
        }
    
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            Movie movie = (Movie)validationContext.ObjectInstance;
    
            if (movie.Genre == Genre.Classic && movie.ReleaseDate.Year > _year)
            {
                return new ValidationResult(GetErrorMessage());
            }
    
            return ValidationResult.Success;
        }
    }
    

    I've adapted the example to exclude client-side validation, as requested in your question.

    In order to use this new attribute (again, taken from the docs), you need to add it to the relevant field:

    [ClassicMovie(1960)]
    [DataType(DataType.Date)]
    public DateTime ReleaseDate { get; set; }
    

    Here's another, simpler example for ensuring that a value is true:

    public class EnforceTrueAttribute : ValidationAttribute
    {
        public EnforceTrueAttribute()
            : base("The {0} field must be true.") { }
    
        public override bool IsValid(object value) =>
            value is bool valueAsBool && valueAsBool;
    }
    

    This is applied in the same way:

    [EnforceTrue]
    public bool ThisShouldBeTrue { get; set; }
    

    Edit: Front-End Code as requested:

    The options are All, ModelOnly or None.

提交回复
热议问题