0

For custom validations in .NET Core I am using the System.ComponentModel.DataAnnotations.ValidationAttribute annotation, and I'm overriding the IsValid method as shown here.

Now I want to add error codes for each error message, so that each error message will have an associated error code as well.

How this can be achieved?

techresearch
  • 119
  • 3
  • 14
  • Have a look at [this answer](https://stackoverflow.com/questions/51733372/custom-error-code-pages-with-message) to create a CustomErrorResponseMiddleware. – Qing Guo Jun 24 '22 at 06:02
  • Hi @techresearch,could you explain your purpose more clearly?Error message is just related with Clientside validate.If the clientside validate failed,you'll get the error message in your page and won't post the data to server side. Or you want to generate an error code just in clientside? – Ruikai Feng Jun 24 '22 at 06:32
  • @RuikaiFeng I am using an http trigger azure function app and here i want to validate the request with the model i have created. So incase of error uses with get json array response with error message and error codes. – techresearch Jun 24 '22 at 06:38

1 Answers1

0

I tried as below,Is it what you want?:

the custom validateAttribute:

public class StringLengthRangeAttribute : ValidationAttribute
    {
        public int Minimum { get; set; }
        public int Maximum { get; set; }

         public Dictionary<int, string> ErrorMessageDic { get; set; } = new Dictionary<int, string>();
        public StringLengthRangeAttribute()
        {
            this.Minimum = 5;
            this.Maximum = 10;
            ErrorMessageDic.Add(0, "SomeError");
            ErrorMessageDic.Add(1, "Minlength=5");
            ErrorMessageDic.Add(2, "Maxlength=10");
        }
        
        protected override ValidationResult? IsValid(
        object? value, ValidationContext validationContext)
        {
            string strValue = value as string;

            if (strValue.Length < this.Minimum)
            {
                return new ValidationResult(GetErrorMessage(1));
            }
            else if (strValue.Length > this.Maximum)
            {
                return new ValidationResult(GetErrorMessage(2));
            }
            return ValidationResult.Success;
        }
        public string GetErrorMessage(int key)
        {
            if (ErrorMessageDic.ContainsKey(key))
            {
                return string.Format("errorcode:[{0}],errormessage:[{1}]", key, ErrorMessageDic[key]);
            }
            return ErrorMessageDic[0];
        }

    }

Model:

 public class TargetModel
    {
        [StringLengthRange]
        public string TestStr1 { get; set; }
        [StringLengthRange]
        public string TestStr2 { get; set; }
    }

The testResult: enter image description here

Ruikai Feng
  • 6,823
  • 1
  • 2
  • 11