本文介绍了自定义属性的不显眼的jQuery客户端验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了的服务器端(形式发布后)自定义验证属​​性,但我不能去上班的客户端验证。

I have created a custom validation attribute which works server-side (after form is posted) but I cannot get the validation to work client-side.

自定义属性是:

public class ReasonableAttribute : ValidationAttribute, IClientValidatable
{
    public override bool IsValid(object value)
    {
        return Approval.IsNumberReasonable(value.ToString());
    }

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        ModelClientValidationRule rule = new ModelClientValidationRule();
        rule.ErrorMessage = FormatErrorMessage(metadata.GetDisplayName());
        rule.ValidationType = "reasonable";
        yield return rule;
    }

}

IsNumberReasonable()功能少了点上的字段输入一些检查,以使他们进入知道什么可以合理是一个批准文号(如不为空,或未知或者类似的东西)返回一个布尔真/假

The IsNumberReasonable() function just does some checks on the fields input to make sure what they entered could reasonably be an Approval number (e.g. not empty, or "Unknown" or something like that) returning a bool true/false.

然后我的模型包括:

[Display(Name = "Approval Number"]
[Reasonable(ErrorMessage = "Please enter a reasonable {0}")]
public String ApprovalNumber { get; set; }

和视图包含:

@Html.LabelFor(model => model.ApprovalNumber, new { @class = "control-label col-md-3" })
<div class="col-md-9 append field">
 @Html.TextBoxFor(model => model.ApprovalNumber, new { @class = "input text" })
 @Html.ValidationMessageFor(model => model.ApprovalNumber)
</div>

在JavaScript中我曾尝试加入:

in the JavaScript I have tried adding:

$.validator.unobtrusive.adapters.addBool("reasonable", "required");
// OR
$.validator.unobtrusive.adapters.add("reasonable");

和:(的document.ready以外)

and: (outside of document.ready)

(function ($) {
            $.validator.addMethod('reasonable', function (value, element, params) {
                return value != '';
            }, 'Clientside Should Not Postback');
            $.validator.unobtrusive.adapters.addBool('reasonable');
        })(jQuery);

在不同的组合,但一直没能得到它的工作。

in various combinations but have not been able to get it to work.

我有

<script src="~/Scripts/jquery.validate.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.js"></script>

列入查看。

当表单提交,客户端验证适用于其他领域(必需的实用等),但验证消息旁边ApprovalNumber永远不会出现/不执行我的自定义验证。

When the form is submitted, client-side validation works for other fields (required ones etc) but the validation message next to the ApprovalNumber never appears/does not perform my custom validation.

在正确的方向的任何指针是AP preciated。
谢谢。

Any pointers in the right direction are appreciated.thanks.

我也有

<configuration>
  <appSettings>
   <add key="ClientValidationEnabled" value="true" />
   <add key="UnobtrusiveJavaScriptEnabled" value="true" />
  </appSettings>
</configuration>

早在Web.config文件中。

Already in the Web.config file.

编辑2:
根据chenZ的帖子:
为输入域的HTML是:

Edit 2:as per chenZ's post:The html for the input field is:

<input class="input text valid" data-val="true" data-val-reasonable="Please enter a reasonable Approval Number" data-val-required="Approval Number is Required." id="ApprovalNumber" name="ApprovalNumber" type="text" value="">

尝试过更新我的看法与底部:

Tried updating the bottom of my view with:

<script src="~/Scripts/jquery.validate.js"></script>
<script type="text/javascript">
    (function ($) {
        $.validator.addMethod('reasonable', function (value, element, params) {
            return value != '';
        }, 'Clientside Should Not Postback');
    })(jQuery);
    </script>

    <script src="~/Scripts/jquery.validate.unobtrusive.js"></script>
<script src="~/Scripts/Create.js"></script>

其中, jquery.validate.unobtrusive.js 的末尾现在包含:

    $(function () {
        $.validator.unobtrusive.adapters.addBool('reasonable');
        $("#formID").removeData("unobtrusiveValidation").removeData("validator");
        $jQval.unobtrusive.parse(document);
    });
}(jQuery));

create.js 包含:

$.validator.unobtrusive.adapters.addBool("mandatory", "required"); // another custom attribute for checkbox validation
    var v = $("#formID").validate({
        errorClass: "warning",
        onkeyup: false,
        onblur: false,
    });

v 变量用于进一步向下的提交按钮:

the v variable is used further down for the submit button:

$("#SubmitButton").click(function () {
    if (v.form()) {
          // The form passed validation so continue..
        } else {
            // Validation failed, do something else..
        }
});

我做了一些进一步的测试ANS似乎被什么东西做的:

I did some further testing ans it appears to be something to do with the:

(function ($) {
            $.validator.addMethod('reasonable', function (value, element, params) {
                return value != '';
            }, 'Clientside Should Not Postback');
        })(jQuery);

当我将其更改为:

(function ($) {
            $.validator.addMethod('reasonable', function (value, element, params) {
                return value != 'unknown';
            }, 'Clientside Should Not Postback');
        })(jQuery);

它的工作原理,但只有当我键入未知在输入框中,别的传递。同样,如果我把返回值='jhdsfkhsdkfj';!它只验证,当我输入的 jhdsfkhsdkfj

it works, but only if I type 'unknown' into the input box, anything else passes.. similarly if I put return value != 'jhdsfkhsdkfj'; it only validates when I input jhdsfkhsdkfj.

这样看来,它正在使用的规则?而不是我的服务器端 IsNumberReasonable()功能。

so it appears that it is using that as the rule? instead of my server-side IsNumberReasonable() function.

希望帮助排除故障。

推荐答案

我还没有尝试过,所以我不知道,但我认为有2个地方,你可能是错的。

I haven't tried it, so I'm not sure, but i think there are 2 places where you may be wrong.

1.rule.ValidationType =合理;结果
检查你的HTML,找到输入,是有生成的attr数据-VAL-reasonalbe或reasonale

1.rule.ValidationType = "reasonable";
Check your html, find the input and is there an attr data-val-reasonalbe or reasonale

$.each(this.adapters, function () {
            var prefix = "data-val-" + this.name,

在jquery.validate.unobtrusive.js,173线,可以发现这一点,所以它必须是一个数据-VAL-XXXX

in jquery.validate.unobtrusive.js, line 173, you can find this, so it must be a data-val-xxxx

文件2.in jquery.validate.unobtrusive.js结束时,你可以找到

2.in jquery.validate.unobtrusive.js end of file you can find

$(function () {
    $jQval.unobtrusive.parse(document);
});

所以,当加载页面时,所有形式的validate集

so, when the page is loaded, all form set validate

这是一件很难的事情。
如果你的code是像

This is a difficult thing.If your code is like

<script src="~/Scripts/jquery.validate.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.js"></script>
.....
(function ($) {
        $.validator.addMethod('reasonable', function (value, element, params) {
            return value != '';
        }, 'Clientside Should Not Postback');
        $.validator.unobtrusive.adapters.addBool('reasonable');
    })(jQuery);

当你做unobtrusive.parse(文件);您的合理的有效的方法不存在,并且适配器不存在或者存在的,所以你的形式有效没有合理的规则

When you do unobtrusive.parse(document); your valid method reasonable doesn't exist, and adapter doesn't exist exist either, so your form valid doesn't have a rule reasonable

如果你改变了code喜欢这个

If you change the code to like this

<script src="~/Scripts/jquery.validate.js"></script>
(function ($) {
        $.validator.addMethod('reasonable', function (value, element, params) {
            return value != '';
        }, 'Clientside Should Not Postback');
        $.validator.unobtrusive.adapters.addBool('reasonable');
    })(jQuery);
<script src="~/Scripts/jquery.validate.unobtrusive.js"></script>

有效的方法可以添加,但$ .validator.unobtrusive未定义

the valid method can add, but the $.validator.unobtrusive is undefined

我认为你应该做更多的

<script src="~/Scripts/jquery.validate.js"></script>
(function ($) {
        $.validator.addMethod('reasonable', function (value, element, params) {
            return value != '';
        }, 'Clientside Should Not Postback');
    })(jQuery);
<script src="~/Scripts/jquery.validate.unobtrusive.js"></script>

,把

$.validator.unobtrusive.adapters.addBool('reasonable');

中jquery.validate.unobtrusive.js,并确保它之前

in to jquery.validate.unobtrusive.js, and make sure it runs before

$(function () {
    $jQval.unobtrusive.parse(document);
});

我不知道它是否会奏效,也许我会稍后再试。
希望这可以帮助你。

I'm not sure if it will work, maybe I'll try later.Hope this can help you.

更新
我试了一下。
在第2点,你可以用code

updateI tried it.In point 2, you can use code

$(function () {
    $("#formid").removeData("unobtrusiveValidation").removeData("validator");
    $.validator.unobtrusive.parse(document);
});

将这个code后,您添加有效的方法,这将清零有效设置和自定义规则解析再次

Put this code after your add valid method, this will clear valid setting and parse again with your custom rules

更新2

$("#a").validate({});//first time call is useful
$("#a").validate({});//second time call is useless

也unobtrusive.parse(...)

also to unobtrusive.parse(...)

jquery.validate.js 41行

jquery.validate.js line 41

var validator = $.data( this[0], "validator" );
if ( validator ) {
    return validator;
}

和jquery.validate.unobtrusive.js 99行

and jquery.validate.unobtrusive.js line 99

result = $form.data(data_validation),
    ...
    if (!result) { ....

&LT;脚本SRC =〜/脚本/ jquery.validate.unobtrusive.js&GT;&LT; / SCRIPT&GT; 结果
该文件的结束时,称为unobtrusive.parse(文件)时,将附加数据以形成。
如果你设置code之前调用,验证设置是没有您的设置。
你可以removeData(...),并通过您的code再喜欢

when <script src="~/Scripts/jquery.validate.unobtrusive.js"></script>
end of this file, called unobtrusive.parse(document), it will append a data to form.If it called before you setup code, the validate setting is without your setup.you can removeData(...), and run unobtrusive.parse(document) by your code again like

<script src="~/Scripts/jquery.validate.unobtrusive.js"></script>
<script src="~/Scripts/setting.js"></script>
<script>
  $(function(){ $("#formid").removeData(...).removeData(...);
  ....unobtrusive.parse(document)});
</script>

验证插件使用的数据名称为验证和不显眼的数据使用的名称unobtrusiveValidation。

validate plugin use data name "validator" and unobtrusive use data name "unobtrusiveValidation".

我为我的英语不好真的很抱歉,希望你能理解。

I'm really sorry for my poor English, hope you can understand.

这篇关于自定义属性的不显眼的jQuery客户端验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-28 00:23