如何使用jQuery改变MVC定制的客户端验证错误消息在运行时? [英] How to change MVC custom client-side validation error message at runtime using jQuery?

查看:108
本文介绍了如何使用jQuery改变MVC定制的客户端验证错误消息在运行时?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用MVC5,我有我的视图,其中包含一个简单的形式与以下字段的视图模型:

I am using MVC5, and I have a ViewModel for my View, which contains a simple form with the following fields:

MinFirstNameLength
FirstName
MinLastNameLength
LastName

现在,我谨应用验证规则,根据 MinFirstNameLength 的价值,同样为使用 MinLastNameLength 。我想这样做对客户端了。

Now, I wish to apply a validation rule on FirstName, based on the value of MinFirstNameLength, and similarly for LastName using MinLastNameLength. I want to do this on the client-side too.

所以,我用MVC的不显眼的客户端验证功能。我做了一个自定义验证属​​性,贯彻 IClientValidatable 接口。在 GetClientValidationRules 方法是这样的:

So, I used MVC's unobtrusive client side validation feature. I made a custom validation attribute, implementing the IClientValidatable interface. The GetClientValidationRules method looks like this:

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

此验证属性是应用在这样的特性:

This validation attribute is applied on the FirstName and LastName properties like this:

[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文件的客户端验证功能,它看起来像这样:

Also, I have the client side validation functions in a .js file elsewhere, which looks like this:

$.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;
});

我的问题是,我怎么了 MinFirstNameLength 在文本框中的值赋给占位符 {0} 我的错误信息,使该错误信息读取名字必须至少[值]字符

My question is, how do I assign the value in the textbox for MinFirstNameLength to the placeholder {0} in my error message for FirstName, so that the error message reads First Name must be at least [value] characters?

我尝试添加修改我的 $ validator.unobtrusive.adapters.add 方法如下:

I tried adding modifying my $.validator.unobtrusive.adapters.add method as follows:

$.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标记并切换到适当的修改错误,但这种变化并没有反映在页面中。

But both these tricks didn't work. The HTML markup did change to modify the error appropriately, but this change wasn't reflected in the page.

目前,该错误消息我看到的是:

Currently, the error message I see is:

名字必须至少#FirstNameMinLength字符

占位符是由被用作验证规则的参数控制的ID自动替换。

The placeholder is replaced automatically by the id of the control which is used as a parameter in the validation rule.

在哪里此错误消息从何而来?我如何在运行时修改它?

Where does this error message come from? How do I modify it at runtime?

推荐答案

我觉得你应该只格式化你的服务器端的消息在NameMinLength验证属性的IsValid方法。下面是关于如何做到这一点的一个小例子。

I think you should just format your message on server side in the IsValid method of your NameMinLength validation attribute. Here's a small example on how to do it.

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属性正确的值替换占位符。在这种情况下,错误信息将它移动到客户端之前对其进行格式化。所以需要这种没有额外的逻辑。

This should replace the placeholder with the correct value from MinLengthPropName property. In this case the error message will be formatted before moving it to client side. So no additional logic required for this.

编辑:
嗯,只是想您可能希望根据用户输入这实在是奇怪验证。其实,事实上,你可能有不同的最小长度的限制为同一字段没有道理给我,但只要它不是基于用户输入的它是更安全的。

Hm, just thought that you might want to validate based on user input which is really wierd. Actually the fact that you might have different min length restrictions for the same field doesn't make sense to me but as long as it' not based on user input it is much more secure.

使用客户端解决方案更新时间:结果
我做了一个简单的测试具有相似的属性,它为我的作品

UPDATED WITH CLIENT SIDE SOLUTION:
I did a simple test with a similar attribute and it works for me

编辑模型:

[MinCustomLength("MinLenthDestURI", "Dest URI must be at least {0} characters")]
public string DestinationURI { get; set; }
public int MinLenthDestURI { get; set; }

属性code:

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

客户端code:

Client side code:

$.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;
    }
});

这将取代{0}从MinLenthDestURI文本框的值时,验证完成。

This will replace {0} with a value from MinLenthDestURI textbox when validation is done.

希望它帮助!

这篇关于如何使用jQuery改变MVC定制的客户端验证错误消息在运行时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆