[英]Change error message for ASP.NET custom validator using javascript (client-side validation)?
[英]How to change MVC custom client-side validation error message at runtime using jQuery?
我正在使用MVC5,并且我的View有一个ViewModel,其中包含具有以下字段的简单表单:
MinFirstNameLength
FirstName
MinLastNameLength
LastName
现在,我希望基于MinFirstNameLength
的值在FirstName
上应用验证规则,类似地,对使用MinLastNameLength
LastName
应用验证规则。 我也想在客户端这样做。
因此,我使用了MVC的客户端验证功能。 我创建了一个自定义验证属性,实现了IClientValidatable
接口。 GetClientValidationRules
方法如下所示:
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
string ErrorMessage = ErrorMessageString;
ModelClientValidationRule NameMinLengthRule = new ModelClientValidationRule();
NameMinLengthRule.ErrorMessage = ErrorMessage;
NameMinLengthRule.ValidationType = "nameminlength";
NameMinLengthRule.ValidationParameters.Add("minlengthpropname", MinLengthPropName);
yield return NameMinLengthRule;
}
此验证属性将应用于FirstName
和LastName
属性,如下所示:
[NameMinLength("FirstNameMinLength",ErrorMessage = "First Name must be at least {0} characters"]
public string FirstName { get; set; }
[NameMinLength("LastNameMinLength",ErrorMessage = "Last Name must be at least {0} characters"]
public string LastName { get; set; }
另外,我在其他地方的.js文件中具有客户端验证功能,如下所示:
$.validator.addMethod("nameminlength",
function (
value,
element,
params
) {
return value.length >= parseInt($(params).val());
});
$.validator.unobtrusive.adapters.add("nameminlength", ["minlengthpropname"], function (options) {
var paramField = "#" + options.params.minlengthpropname;
options.rules["nameminlength"] = paramField;
var errormessage = options.message;
options.messages["nameminlength"] = errormessage;
});
我的问题是,如何在我的FirstName
错误消息MinFirstNameLength
文本框中的值分配给占位符{0}
,以便错误消息显示First Name must be at least [value] characters
?
我尝试添加修改$.validator.unobtrusive.adapters.add
方法,如下所示:
$.validator.unobtrusive.adapters.add("nameminlength", ["minlengthpropname"], function (options) {
var paramField = "#" + options.params.minlengthpropname;
options.rules["nameminlength"] = paramField;
var errormessage = options.message;
options.messages["nameminlength"] = errormessage;
$(paramField).blur(function () {
// change error message in the 'data-val-nameminlength' attribute of the HTML element on which validation is applied
var newErrorMessage = options.messages["nameminlength"].replace("{0}", $(paramField).val());
$(options.element).attr("data-val-nameminlength", newErrorMessage);
// change error message inside the error message span generated for displaying this error
$(options.element).siblings(".field-validation-valid").html(newErrorMessage);
});
});
但是这两种技巧都没有用。 HTML标记确实进行了更改以适当地修改错误,但是此更改未反映在页面中。
目前,我看到的错误消息是:
First Name must be at least #FirstNameMinLength characters
占位符将自动替换为控件的ID,该ID在验证规则中用作参数。
此错误消息从何而来? 如何在运行时修改它?
我认为您应该只使用NameMinLength验证属性的IsValid方法在服务器端格式化消息。 这是一个有关如何执行此操作的小示例。
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var conditionalPropertyInfo = validationContext.ObjectType.GetProperty(this.MinLengthPropName);
var conditionalPropertyValue = conditionalPropertyInfo.GetValue(validationContext.ObjectInstance, null);
this.ErrorMessage = string.Format(this.ErrorMessage, conditionalPropertyValue.ToString())
// YOUR OTHER CODE HERE
}
这应该使用MinLengthPropName属性中的正确值替换占位符。 在这种情况下,错误消息将被格式化,然后再将其移至客户端。 因此,此操作不需要其他逻辑。
编辑:嗯,只是认为您可能想根据确实很奇怪的用户输入进行验证。 实际上,您可能对同一字段具有不同的最小长度限制这一事实对我来说没有意义,但只要它不是基于用户输入的,它就会更加安全。
使用客户端解决方案进行了更新:
我做了一个具有类似属性的简单测试,对我有用
编辑模型:
[MinCustomLength("MinLenthDestURI", "Dest URI must be at least {0} characters")]
public string DestinationURI { get; set; }
public int MinLenthDestURI { get; set; }
属性代码:
public class MinCustomLengthAttribute : ValidationAttribute, IClientValidatable
{
private String PropertyName { get; set; }
public MinCustomLengthAttribute(String propertyName, String errormessage)
{
this.PropertyName = propertyName;
this.ErrorMessage = errormessage;
}
protected override ValidationResult IsValid(object value, ValidationContext context)
{
// Just for test server side validation always returns Success
return ValidationResult.Success;
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var modelClientValidationRule = new ModelClientValidationRule
{
ValidationType = "mincustomlength",
ErrorMessage = this.ErrorMessage
};
modelClientValidationRule.ValidationParameters.Add("prop", PropertyName);
yield return modelClientValidationRule;
}
}
客户端代码:
$.validator.addMethod("mincustomlength", function (value, element, params) {
var conditionalId = $.validator.getId(element, params.prop);
var minLength = parseInt($("#" + conditionalId).val());
if (value.length < minLength) {
var message = $(element).attr('data-val-mincustomlength');
$.validator.messages.mincustomlength = $.format(message, minLength);
return false;
}
return true;
});
$.validator.unobtrusive.adapters.add('mincustomlength', ['prop'], function (options) {
options.rules['mincustomlength'] = options.params;
if (options.message != null) {
$.validator.messages.mincustomlength = options.message;
}
});
验证完成后,它将用MinLenthDestURI文本框中的值替换{0}。
希望能帮助到你!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.