2

Imagine that I have an endpoint that accepts optional MyParam string array attribute. How to check it if it's null or empty with most basic way - Data Annotations would be the best.

https://stackoverflow.com/questions/ask?MyParam=

  • [Required] is not an option as parameter has to be optional
  • [StringLength] with MinimumLength doesn't work
  • [MinLength] doesn't work at all
  • [RegularExpression(@"\S+")] doesn't work at all

Update: I want to do it on string array not just string, sorry about confusion. Hope this help to justify why above DataAnnotations don't work.

4
  • and what's the use of this Desired DataAnnotation, how would you use it? Commented Mar 19, 2022 at 0:19
  • It should simply return error when the param is empty or null. Commented Mar 20, 2022 at 11:08
  • You can mark it as [Required] and Check if ModelState.IsValid(), if its not return an error from the controller. Commented Mar 20, 2022 at 22:41
  • It doesn't make sense. Parameter has to be optional, IsValid() just checks if it was provided or not - still can accept empty string. Commented Mar 21, 2022 at 7:39

1 Answer 1

2

I think what you're looking at here is a custom model validation attribute.

For example:

public class MyParamValidationAttribute : ValidationAttribute
{
    public MyParamAttribute(string param)
    {
        Param = param;
    }

    public string Param { get; }

    public string GetErrorMessage() =>
        $"Invalid param value {param}.";

    protected override ValidationResult IsValid(object value,
        ValidationContext validationContext)
    {
        var myParam = (string)value;

        if (string.IsNullOrEmpty(myParam))
        {
            return new ValidationResult(GetErrorMessage());
        }

        return ValidationResult.Success;
    }
}

https://learn.microsoft.com/en-us/aspnet/core/mvc/models/validation?view=aspnetcore-3.1#custom-attributes-1

Sign up to request clarification or add additional context in comments.

1 Comment

I have also updated my question to justify why other DataAnnotations don't work - I mean string array attribute, not just string, still your answer looks valid with minor editing.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.