不显眼的客户端验证规则中的验证类型名称必须是唯一的。以下验证类型不止一次出现:必需

时间:2015-01-21 04:57:18

标签: c# asp.net-mvc validation custom-validators

我创建了自定义ASP.Net MVC模型验证,如下所示:

internal class LocalizedRequiredAttribute : RequiredAttribute, IClientValidatable 
{
    public List<string> DependentProperties { get; private set; }
    public List<string> DependentValues { get; private set; }
    public string Props { get; private set; }
    public string Vals { get; private set; }
    public string RequiredFieldValue { get; private set; }

    public LocalizedRequiredAttribute(string resourceId = "")
    {
        if (string.IsNullOrEmpty(resourceId))
            ErrorMessage = ResourcesHelper.GetMessageFromResource("RequiredValidationErrorMessage");
        else
            ErrorMessage = ResourcesHelper.GetMessageFromResource(resourceId);
    }

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        string msg = FormatErrorMessage(metadata.GetDisplayName());
        yield return new ModelClientValidationRequiredRule(msg); //Exception
    }
}
internal class LocalizedNumericRegularExpressionAttribute : RegularExpressionAttribute, IClientValidatable 
{
    public LocalizedNumericRegularExpressionAttribute(string resourceId = "") : base(@"^\d+$")
    {
        if (string.IsNullOrEmpty(resourceId))
            ErrorMessage = ResourcesHelper.GetMessageFromResource("NumberRequiredValidationErrorMessage");
        else
            ErrorMessage = ResourcesHelper.GetMessageFromResource(resourceId);
    }

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        string msg = FormatErrorMessage(metadata.GetDisplayName());
        yield return new ModelClientValidationRequiredRule(msg); //Exception
    }
}

以下是我的模特:

public class MyModel
{
   [LocalizedRequired]
   [LocalizedNumericRegularExpression]
   public int Emp_No { get; set; }
}

每当我使用上面的模型导航到表单时,就会发生以下异常。

Validation type names in unobtrusive client validation rules must be unique. The following validation type was seen more than once: required
如果删除IClientValidatable

上面的代码就可以,但客户端验证不起作用。

我的代码出了什么问题?

2 个答案:

答案 0 :(得分:2)

我找到了解决方案,我们必须在global.asax

中的Application_Start中添加以下代码
DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(LocalizedRequiredAttribute), typeof(RequiredAttributeAdapter));
DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(LocalizedNumericRegularExpressionAttribute), typeof(RegularExpressionAttributeAdapter));

答案 1 :(得分:0)

您将ValidationType的值与MVC自动验证相同。因此,您必须更改ValidationType =&#34; name unique&#34;的值。在ModelClientValidationRule或其派生类中。名称应该避免MVC自动生成名称,例如&#39; date&#39;,&#39; required&#39; ... 其他解决方案是通过将这些代码放在app start

来关闭自动验证

DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false;