问题
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
}
}
the following is my Model:
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
above codes are OK if I remove IClientValidatable
, but the client validation doesn't work.
What's wrong with my code?
回答1:
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));
回答2:
You put value of ValidationType same with MVC auto validate. So, you must change the value of ValidationType = "name unique" in ModelClientValidationRule or its derived class. Name should avoid MVC auto generate name such as 'date', 'required'... Other solution is turn off auto validate by put these code on app start
DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false;
来源:https://stackoverflow.com/questions/28059904/validation-type-names-in-unobtrusive-client-validation-rules-must-be-unique-the