Manually validate Model in Web api controller

前端 未结 4 486
梦毁少年i
梦毁少年i 2020-12-31 20:24

I have a class called \'User\' and a property \'Name\'

public class User
{
    [Required]
    public string Name { get; set; }
}

And api co

4条回答
  •  攒了一身酷
    2020-12-31 21:02

    You will need to define custom Validation Attribute as

    class CustomValidatorAttribute : ValidationAttribute
    {
      //custom message in ctor
      public CustomValidator() : base("My custom message") {}
      public CustomValidator(string Message) : base(Message) {}
      public override bool IsValid(object value)
      {
         return !string.IsNullOrWhiteSpace(value.ToString());
      }
      //return a overriden ValidationResult
      protected override ValidationResult IsValid(Object value,ValidationContext validationContext)
      {
         if (IsValid(value)) return ValidationResult.Success;
         var message = "ohoh";
         return new ValidationResult(message);
      }
     }
    

    likewise in your model class

    public class User
    {
      [Required]
      [CustomValidator("error")]
      public string Name { get; set; }
    }
    

提交回复
热议问题