本文介绍了不打扰的客户端验证规则中的验证类型名称必须唯一。多次看到以下验证类型:必需的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了以下自定义ASP.Net MVC模型验证:

I created custom ASP.Net MVC model validation as the following:

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

每当我使用上述模型导航至表单时,都会发生以下异常。

Whenever I navigate to form with above Model, the following exception has occurred.

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

如果我删除<$ c,上述代码也可以$ c> IClientValidatable ,但客户端验证无效。

above codes are OK if I remove IClientValidatable, but the client validation doesn't work.

我的代码有什么问题?

推荐答案

我找到了解决方案,我们必须在global.asax的Application_Start处添加以下代码

I found the solution, We have to add the following codes at Application_Start in global.asax

DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(LocalizedRequiredAttribute), typeof(RequiredAttributeAdapter));
DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(LocalizedNumericRegularExpressionAttribute), typeof(RegularExpressionAttributeAdapter));

这篇关于不打扰的客户端验证规则中的验证类型名称必须唯一。多次看到以下验证类型:必需的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 17:48