1

I have two fields in one of my class for address like

public string Country { get; set; }
[Required(ErrorMessage = "Postcode is required")]
[RegularExpression(@"REGEX", 
ErrorMessage = "Please enter a valid UK Postcode)]
public string postcode { get; set;}

However if the user selects a country other than UK then I want my Postcode field to ignore the REGEX atleast and in an ideal world validate using another REGEX depending upon the country. Can anyone suggest if this is possible in the model itself?

Flood Gravemind
  • 3,773
  • 12
  • 47
  • 79

2 Answers2

2

There are a few different options for you:

  1. Create a 100% custom validation attribute that combines the Required and RegularExpression attributes to your needs. So inside that custom attribute you would do all the validation that you need and compare the value to the Country property to selectively apply the RegEx as needed.

  2. Create a different postcode attribute per country that you care about and use something like the `RequiredIfAttribute (see RequiredIf Conditional Validation Attribute) to determine which one is actually required. You can then use Javascript to show/hide the appropriate input fields.

Community
  • 1
  • 1
Matt Houser
  • 33,983
  • 6
  • 70
  • 88
2

You can do this with IValidatableObject:

class MyClass : IValidatableObject {

   public string Country { get; set; }

   [Required(ErrorMessage = "Postcode is required")]
   public string postcode { get; set;}

   public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) {

      if (!String.IsNullOrEmpty(Country) 
         && !String.IsNullOrEmpty(postcode)) {

         switch (Country.ToUpperInvariant()) { 
            case "UK":
               if (!Regex.IsMatch(postcode, "[regex]"))
                  yield return new ValidationResult("Invalid UK postcode.", new[] { "postcode" });
               break;

            default:
               break;
         }
      }
   }
}
Max Toro
  • 28,282
  • 11
  • 76
  • 114