How to create Custom Data Annotation Validators

Viewed 80218

Wanting to create custom data annotation validation. Are there any useful guides / samples on how to create them?

Firstly:
StringLength with minimum and maximum length. I'm aware .NET 4 can do this, but want to do the same in .NET 3.5, if possible being able to define minimum length only (at least x chars), maximum length only (up to x chars), or both (between x and y chars).

Secondly:
Validation using modulus arithmetic - if the number is a valid length, I wish to validate using the Modulus 11 algorithm (I have already implemented it in JavaScript, so I guess it would just be a simple porting?)

Update:
Solved second problem, was just a case of copying over the JavaScript implementation and making a few tweaks, so don't need a solution for that.

3 Answers

I know this is a really old topic but I had trouble finding the answer I actually wanted until I found this answer.

To summarise it, you need to configure the service on startup, creating appropriate objects that handle the error you want to return:

services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2).ConfigureApiBehaviorOptions(options =>
        {
            options.InvalidModelStateResponseFactory = (context) =>
            {
                var errors = context.ModelState.Values.SelectMany(x => x.Errors.Select(p => new ErrorModel()
               {
                   ErrorCode = ((int)HttpStatusCode.BadRequest).ToString(CultureInfo.CurrentCulture),
                    ErrorMessage = p.ErrorMessage,
                    ServerErrorMessage = string.Empty
                })).ToList();
                var result = new BaseResponse
                {
                    Error = errors,
                    ResponseCode = (int)HttpStatusCode.BadRequest,
                    ResponseMessage = ResponseMessageConstants.VALIDATIONFAIL,

                };
                return new BadRequestObjectResult(result);
            };
       });
Related