Validate model on specific string values

后端 未结 3 672

I\'m working on a Web API 2 project. besides the requirement that some properties are required, some only can have specific values. One option is that I could try to save the m

3条回答
  •  花落未央
    2021-02-07 04:33

    To validate the Gender property I've created a custom validation attribute by creating a new class (attribute):

    using System;
    using System.Collections.Generic;
    using System.Web;
    using System.ComponentModel.DataAnnotations;    
    
    namespace MyProject.Models.Validation
    {
    
        public class StringRangeAttribute : ValidationAttribute
        {
            protected override ValidationResult IsValid(object value, ValidationContext validationContext)
            {
    
                if(value.ToString() == "M" || value.ToString() == "F")
                {
                    return ValidationResult.Success;
                }
    
    
                return new ValidationResult("Please enter a correct value");
            }
        }
    }
    

提交回复
热议问题