I'm writing a custom validation attribute for validating the model and I need some additional information other than what ValidationResult offers. I need to return ErrorMessage and ErrorCode and access it in the controller class so that I can send it in the response payload.
public class CustomValidationResult : ValidationResult
{
public int ErrorCode { get; set; }
protected CustomValidationResult(ValidationResult validationResult) : base(validationResult)
{
}
}
public class Mandatory : RequiredAttribute
{
public int ErrorCode { get; set; }
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
ErrorCode = 10;
var result = base.IsValid(value, validationContext);
ErrorCode = 10;
return new CustomValidationResult(result)
{
ErrorCode = ErrorCode
};
}
}
I need to get the ErrorCode out in the controller, if ModelState.IsValid fails.
Thanks in advance.
ErrorCodeifModelState.IsValidfails? It is impossible to extendclass property, and you could not customValidationResultwhich is defined inValidationAttribute. For a workaound, I suggest you try to store error code in error message like[Required(ErrorMessage ="[400]Name is required")], and then getError Code 400fromErrorMessage.ErrorCode? Do you only use this inControllerlikeModelState.IsValid, or you will use it in theView? If later, I am afriad it is impossible. If previous, you may consider define static class to valide the model by your self instead of usingModelState.IsValid. Anyway, it is also complex. I am wondering whether thisErrorCodeis requrired since I did not see any meaning for it while validing Model.