Frage

How can I access ModelState from custom validator for adding errors?

class CustomValidator : ValidationAttribute
{

    public override bool IsValid(object value)
    {
       //access modelstate
    }
}
War es hilfreich?

Lösung

Well the bool IsValid method will just add an error in ModelState when returning false. You don't have to manage ModelState directly.

If you want a custom message, you can do it on the ctor.

If you want more control, you may override ValidationResult IsValid( Object value, ValidationContext validationContext )

class CustomValidator : ValidationAttribute
{
    //custom message in ctor
    public CustomValidator() : base("My custom message") {}
    public override bool IsValid(object value)
    {
       return true;
    }
    //return a overriden ValidationResult
    protected override ValidationResult IsValid(
    Object value,
    ValidationContext validationContext) {

      var message = "ohoh";
      return new ValidationResult(message);
   }


}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top