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

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

我创建了自定义 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,上面的代码是可以的,但是客户端验证不起作用。

我的代码有什么问题?

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

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

您将 ValidationType 的值设置为与 MVC 自动验证相同。因此,您必须在 ModelClientValidationRule 或其派生的 class 中更改 ValidationType = "name unique" 的值。名称应避免 MVC 自动生成名称,例如 'date'、'required'... 其他解决方案是通过将这些代码放在应用程序启动

上来关闭自动验证

DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = 假;