如何在流畅验证中验证自定义依赖验证?比如验证不同国家的邮政编码

时间:2015-03-25 05:26:15

标签: asp.net-mvc razor fluentvalidation

我想验证,如, 我有文本框,我想验证网站正在打开的国家/地区的邮政编码。就像我在U.k打开网站一样,当我在文本框中写邮政编码时,文本框应该只使用流利验证验证英国邮政编码。我在这里尝试了一些代码,但它不起作用。

验证器类文件中的

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);
        }

和cshtml页面

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

这里我只尝试这个静态条目进行测试。

1 个答案:

答案 0 :(得分:0)

在您的代码中,您将输入字符串正则表达式值进行比较,并将其误判:您应检查Regex对象是否与字符串匹配。要通过一个正则表达式进行验证,您可以使用Matches规则:

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");
}

如果您需要使用多个正则表达式验证输入字符串 - 请使用Must规则,例如更改验证方法:

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;
}

Matches规则的优点是客户端验证支持,但您不能为一个属性使用多个匹配规则。

相关问题