-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathzipcodeValidator.cs
More file actions
26 lines (21 loc) · 960 Bytes
/
zipcodeValidator.cs
File metadata and controls
26 lines (21 loc) · 960 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
using System.ComponentModel.DataAnnotations;
using System.Text.RegularExpressions;
public class ZipCodeValidationAttribute : ValidationAttribute
{
private static readonly Regex UsZipCodeRegex = new Regex(@"^\d{5}$");
private static readonly Regex CaPostalCodeRegex = new Regex(@"^[A-Za-z]\d[A-Za-z]\s?\d[A-Za-z]\d$");
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (value == null || string.IsNullOrEmpty(value.ToString()))
{
return ValidationResult.Success; // Optional: Treat empty input as valid
}
string input = value.ToString();
// Validate against both USA and Canadian formats
if (UsZipCodeRegex.IsMatch(input) || CaPostalCodeRegex.IsMatch(input))
{
return ValidationResult.Success;
}
return new ValidationResult("Please enter a valid USA ZIP code or Canadian postal code.");
}
}