动态新规则验证无效

时间:2013-04-16 16:20:31

标签: jquery asp.net-mvc jquery-validate

我们最近决定迁移到jquery 1.9.1,由于我们的项目位于ASP.NET MVC 3,因此它包含jquery.validatejquery.validate.unobtrusive。一切正常,这些脚本和MVC 3验证之间的默认集成通过属性属性表现得很好。

然而,自更新以来,我们还必须更新验证脚本,当我们这样做时,那些“即时”添加的规则停止工作。但更奇怪的是它只发生在一些房产上。在其他情况下,通过$(form).validate({//things to validate})规则只需应用。

让我给你一些代码来更好地解释它。这是ViewModel属性(这是一个简化的例子):

[DataType(DataType.Password)]
        [Required(ErrorMessage = "*Required Field")]
        [Remote("ValidatePassword", "Validator", AdditionalFields = "User")]
        public string SenhaAnterior { get; set; }

[HiddenInput]
        public int VerificacaoSeguranca { get; set; }

这是视图

    @using (Html.BeginForm("...", "...", null, FormMethod.Post, new { @id = "formMSenha" }))
        { 
    <div id="container">
    @Html.HiddenFor(model => model.VerificacaoSeguranca, new { @id = "hdSeguranca" })
@Html.ValidationMessageFor(model => model.VerificacaoSeguranca)
    <div>
                    <label>
                        Senha anterior:
                        @Html.PasswordFor(model => model.SenhaAnterior, new { @id = "txtSenhaAnterior" })
                        @Html.ValidationMessageFor(model => model.SenhaAnterior)
                    </label>
                </div>
    </div>
    }

脚本

//Even if try this, it still doesn't work
$('#formMSenha').validate({
                rules: {
                    hdSeguranca: {
                        min: 4
                    }
                },
                messages: {
                    hdSeguranca: 'Your password lacks security. Try harder'
                }
            });

    //Since this is a partial view, i have to parse the new added form so the validation rules apply
    $.validator.unobtrusive.parse($("#formMSenha"));

                //Minimum security level
                $('#hdSeguranca').rules('add', { min: 4, messages: { min: 'Your password lack security. Try adding more numbers, letters ou symbols.'} });

在更新之前,新的添加规则有效,但现在却没有。这就像新规则永远不会被验证器解析或因为它不能识别它。但奇怪的是,如果我这样做

('#formMSenha').validate({
                rules: {
                    txtSenhaAnterior: {
                        min: 4
                    }
                },
                messages: {
                    hdSeguranca: 'New test'
                }
            });

$('#txtSenhaAnterior').rules('add', { min: 4, messages: { min: 'Newer teste'} });

验证适用!我完全不知道为什么。

修改

正如@Sparky所建议的那样,我正在展示这个PartialView的渲染HTML(它是jquery对话框),只是做了一些修改。

<div id="msenhaContainer">
<form method="post" id="formMSenha" action="..." novalidate="novalidate">        <h2>
            Atualize sua senha para uma senha complexa</h2>
        <div id="campos">
            <input type="hidden" value="0" name="VerificacaoSeguranca" id="hdSeguranca" data-val-required="The VerificacaoSeguranca field is required." data-val-number="The field VerificacaoSeguranca must be a number." data-val="true">
            <div>
                <label>
                    Senha anterior:
                    <input type="password" name="SenhaAnterior" id="txtSenhaAnterior" data-val-required="*Campo obrigat&amp;#243;rio" data-val-remote-url="/Validator/ValidarSenhaAnterior" data-val-remote-additionalfields="*.SenhaAnterior,*.Usuario" data-val-remote="&amp;#39;SenhaAnterior&amp;#39; is invalid." data-val="true" class="input-validation-error">
                    <span data-valmsg-replace="true" data-valmsg-for="SenhaAnterior" class="field-validation-error"><span for="txtSenhaAnterior" class="">*Campo obrigatório</span></span>
                </label>
            </div>
            <div>
                <label>
                    Nova Senha: <input type="password" name="SenhaNova" maxlength="18" id="txtSenhaNova" data-val-required="*Campo obrigat&amp;#243;rio" data-val="true" class="valid">
                    <span data-valmsg-replace="true" data-valmsg-for="SenhaNova" class="field-validation-valid"></span>
                </label>
            </div>
            <div>
                <label>
                    Nova Senha Confirmação: <input type="password" name="SenhaNovaConfirmacao" maxlength="18" id="txtSenhaNovaConf" data-val-required="*Campo obrigat&amp;#243;rio" data-val-equalto-other="*.SenhaNova" data-val-equalto="As senhas n&amp;#227;o s&amp;#227;o as mesmas" data-val="true" class="valid">
                    <span data-valmsg-replace="true" data-valmsg-for="SenhaNovaConfirmacao" class="field-validation-valid"></span>
                </label>
            </div>
            <br>
            <label>
                Força da Senha</label>
            <div id="progressoSenha" class="ui-progressbar ui-widget ui-widget-content ui-corner-all" role="progressbar" aria-valuemin="0" aria-valuemax="6" aria-valuenow="2">
            <div class="ui-progressbar-value ui-widget-header ui-corner-left" style="display: block; width: 33%; background: none repeat scroll 0% 0% rgb(209, 125, 14);"></div></div>
            <span data-valmsg-replace="true" data-valmsg-for="VerificacaoSeguranca" class="field-validation-valid"></span>
            <div style="text-align: center" id="descricaoForcaSenha">Fraca</div>
            <a id="regrasSenha" href="#" title="Tooltip com as regras aqui!">Regras da senha complexa</a>
        </div>
<input type="hidden" name="freebird" data-val-required="If i stay, will still remember me" id="freebird"></form></div>

<script type="text/javascript">
    //Xhalent's function
    (function ($) {
        $.validator.unobtrusive.parseDynamicContent = function (selector) {
            //use the normal unobstrusive.parse method
            $.validator.unobtrusive.parse(selector);

            //get the relevant form
            var form = $(selector).first().closest('form');

            //get the collections of unobstrusive validators, and jquery validators
            //and compare the two
            var unobtrusiveValidation = form.data('unobtrusiveValidation');
            var validator = form.validate();

            $.each(unobtrusiveValidation.options.rules, function (elname, elrules) {
                if (validator.settings.rules[elname] == undefined) {
                    var args = {};
                    $.extend(args, elrules);
                    args.messages = unobtrusiveValidation.options.messages[elname];
                    //edit:use quoted strings for the name selector
                    $("[name='" + elname + "']").rules("add", args);
                } else {
                    $.each(elrules, function (rulename, data) {
                        if (validator.settings.rules[elname][rulename] == undefined) {
                            var args = {};
                            args[rulename] = data;
                            args.messages = unobtrusiveValidation.options.messages[elname][rulename];
                            //edit:use quoted strings for the name selector
                            $("[name='" + elname + "']").rules("add", args);
                        }
                    });
                }
            });
        }
    })($);
    //DOM ready
    $(function () {
    //Since this is a test, there's no reason to submit the form to the server
        $.validator.setDefaults({
            debug: true
        });

        //Trying to remove the validator to revalidate the form with the new added rule
        $("#formMSenha").removeData("validator").removeData("unobtrusiveValidation");

        $.validator.unobtrusive.parse($("#formMSenha"));

        $('#hdSeguranca').rules('add', { min: 4, messages: { min: 'Your password lacks security'} });

        //Got this example on Xhalent's blog, but it didn't work either
        //        $.validator.unobtrusive.parseDynamicContent($('#hdSeguranca'));

        $.validator.unobtrusive.parse($("#formMSenha"));

        $('#progressoSenha').progressbar({ max: 6, value: 0 });

        $('#txtSenhaNova').keyup(function () {
            VerifyPasswordStrength($(this).val());
        });

        $('#regrasSenha').tooltip({ content: function () {
            //            var texto = $('&lt;div style="display: inline" &gt;&lt;/div&gt;');
            //            texto.html('Regras da senha complexa:');
            //            texto.append("&lt;ul&gt;").append('&lt;li&gt;').append(
            //            $('&lt;span&gt;').html('Deve possuir pelo menos 6 caracteres')).insertAfter($('&lt;li&gt;').append('&lt;span&gt;').html('Deve ter ao menos um número')).
            //            insertAfter($('&lt;li&gt;').append('&lt;span&gt;').html('Deve ter ao menos um caractere especial. Ex:"! @ # $ % &amp;" '));
            //            return texto;

            var textoSenha = $('#descSenha').html();
            return textoSenha;
        }
        });

        $('#formMSenha').submit(function () {
            $.ajax({
                type: 'post',
                url: '...',
                data: $('#formMSenha').serialize(),
                dataType: 'json',
                success: function (data) {
                    $.growlUI('Sucesso', 'Sucesso', 'Flawlessly done!');

                    setTimeout(function () { window.location.replace('/') }, 2000);
                }
            });

            return false;
        });

    });                                   //JQUERY END
    function VerifyPasswordStrength(password) {
        //Removed the security code, but what it does is validate the input
        //to check if the user abide to the safety rules
        //When everything is done, it assigns a value to the hidden var
        //The mininum score required is 4. So if the user don't hit 4 points
        //it can't let him proceed and submit the form
        $('#hdSeguranca').val(passwordScore);

        var progressbar = $("#progressoSenha");
        var progressbarValue = progressbar.find(".ui-progressbar-value");
        var cor = '#9c9999';

        switch (judite) {
            case 1:
                cor = '#790f0f'; //red
                break;
            case 2:
                cor = '#d17d0e'; //orange
                break;
            case 3:
                cor = '#e1e40b'; //yellow  
                break;
            case 4:
                cor = '#129f0a'; //green
                break;
            case 5:
                cor = '#0768c7'; //blue
                break;
            case 6:
                cor = '#92dae8'; //brighter blue
                break;
        }

        progressbarValue.css({ "background": '' + cor });

        $('#progressoSenha').progressbar("option", "value", passwordScore);

        $('#descricaoForcaSenha').html(desc[passwordScore]);
    }

</script>

2 个答案:

答案 0 :(得分:0)

您尚未展示自己呈现的HTML,但似乎只有 创建和引用id属性。您在.validate()内部用于声明规则的字段名称应该匹配输入的name属性, {{ 1}}。

要使此插件正常工作,所有输入元素都必须包含唯一的id属性。

<强> HTML

name

<强>的jQuery

<input type="text" name="myfield" id="something" />

答案 1 :(得分:0)

似乎在版本1.9之后,验证脚本默认忽略隐藏字段验证。所以我尝试添加验证规则是正确的,问题是它是添加到隐藏字段。

您可以在此处查看更改日志:http://jquery.bassistance.de/validate/changelog.txt

但是如果您需要验证隐藏字段,可以使用下面的代码更改脚本ignore

$.validator.setDefaults({ 
    ignore: [],
    // any other default options and/or rules
});