简体   繁体   中英

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?

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM