0

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?

bubbleking
  • 3,329
  • 3
  • 29
  • 49
  • 1
    Unfortunately, the default model binder tries to save empty strings as a `null` on the model itself, whereas you want to consider it an empty string. I've used a custom model binder that changes this behavior; Someone else might post details before I have a chance to look it up and post the relevant info for you... – Andrew Barber Jun 09 '14 at 17:36
  • 1
    There is an extra attribute you can add to handle this: `[DisplayFormat(ConvertEmptyStringToNull = false)]`, depending on what version of the framework you are using. – Andrew Barber Jun 09 '14 at 17:37

1 Answers1

2

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/

Joanvo
  • 5,677
  • 2
  • 25
  • 35