Search code examples
c#asp.netmodel-validation

How to validate model of so string can be between 10 and 30 characters, or empty - C# ASP.NET


I'm trying to validate incoming JSON using the Required attribute on a model that contains phone numbers. There are two phone number properties, a Primary (required) and Alternate. For the Alternate, I want an empty string to be valid, but strings between 1 and 9 characters and more than 30 characters to be invalid. This does not work:

public class PhoneCreateModel
{
    [Required(AllowEmptyStrings = false,
        ErrorMessageResourceName = "PrimaryPhoneNumberRequired",
        ErrorMessageResourceType = typeof(DataAnnotationMessage))]
    [StringLength(30, MinimumLength = 10,
        ErrorMessageResourceName = "PrimaryPhoneNumberFormat",
        ErrorMessageResourceType = typeof(DataAnnotationMessage))]
    public string Primary { get; set; }

    [StringLength(30, MinimumLength = 10,
        ErrorMessageResourceName = "AlternatePhoneNumberFormat",
        ErrorMessageResourceType = typeof(DataAnnotationMessage))]
    public string Alternate { get; set; }
}

... because it doesn't allow Alternate to be an empty string. How can I allow it to be an empty string OR between 10-30 characters?


Solution

  • You can implement your own validation attribute. It is easier than it seems, just make a class which extends ValidationAttribute, and implement your logic in IsValid function.

    Here's an example: http://www.c-sharpcorner.com/UploadFile/abhikumarvatsa/custom-data-annotations-or-custom-validation-attributes-in-m/