0

i want the validation like, I have text box and i want to validate the postal code for the country where the site being open. like if i open the site in U.k then when i write postal code in textbox the textbox should validate only U.K postal code using fluent validation.i have try some code here but its not working.

in validator class file

public Ekhati_AdminUser_Mst_Validator()
        {
           RuleFor(x => x.Postcode).NotEmpty().Must(IsValidCountryCategory).WithMessage("Select a valid country");
        }

        public bool IsValidCountryCategory(Ekhati_AdminUser_Mst customer, string homeCountry)
        {
            homeCountry = "^(([0-9]{5})*-([0-9]{4}))|([0-9]{5})$";
            var ValidCountries = new List<string>();

            //categorias v�lidas para clientes do tipo R
            ValidCountries.Add("^([A-PR-UWYZ0-9][A-HK-Y0-9][AEHMNPRTVXY0-9]?[ABEHMNPRVWXY0-9]? {1,2}[0-9][ABD-HJLN-UW-Z]{2}|GIR 0AA)$");
            return ValidCountries.Contains(homeCountry);
        }

and in cshtml page

@Html.ValidationMessageFor(model=>model.Postcode, String.Empty, new { @style = "color:red;!important" })

here i try this static entry only for testing.

1 Answers1

0

In your code you compare input string with regexp value and it's mistake: you shoul check if Regex object matches string. For validation by one regular expression you can use Matches rule:

public Ekhati_AdminUser_Mst_Validator()
{
    var homeCountry = "^(([0-9]{5})*-([0-9]{4}))|([0-9]{5})$";

    RuleFor(x => x.Postcode).NotEmpty().Matches(homeCountry).WithMessage("Select a valid country");
}

If you need to validate input string with more than one regexp — use Must rule, like in your example, but change validation method:

public Ekhati_AdminUser_Mst_Validator()
{
    RuleFor(x => x.Postcode).NotEmpty().Must(IsValidCountryCategory).WithMessage("Select a valid country");
}

public bool IsValidCountryCategory(Ekhati_AdminUser_Mst customer, string homeCountry)
{
    var validCountries = new List<Regex>();

    validCountries.Add(new Regex("^([A-PR-UWYZ0-9][A-HK-Y0-9][AEHMNPRTVXY0-9]?[ABEHMNPRVWXY0-9]? {1,2}[0-9][ABD-HJLN-UW-Z]{2}|GIR 0AA)$"));
    validCountries.Add(new Regex("...")); // another regexp

    var validity = true;
    foreach(var regexp in validCountries)
    {
        if (!regexp.IsMatch(homeCountry))
        {
            validity = false;
            break;
        }
    }
    return validity;
}

Advantage of Matches rule is client-side validation support, but you can't use more than one match rule for one property.

David Levin
  • 6,573
  • 5
  • 48
  • 80