代码之家  ›  专栏  ›  技术社区  ›  ChadT

jquery对尚未创建的元素进行验证

  •  6
  • ChadT  · 技术社区  · 17 年前

    我想知道,在最初设置规则时,是否有可能让jQuery Validator插件验证dom中尚不存在的元素。

    我正在使用的验证程序的主页: http://bassistance.de/jquery-plugins/jquery-plugin-validation/

    http://ejohn.org/blog/javascript-micro-templating/

    <script type="text/html" id="ProductsTemplateEdit">
        <td>
            <input type="hidden" value="<#= item.ID #>" id="Edit.ID" name="Edit.ID" />
            <input type="text" value="<#= item.Price#>" id="Edit.Price" name="Edit.Price" />
        </td>
    </script>
    

    这些值显然是通过传入的json填充的。

    我还应该提到,我正在使用xval验证框架,它基本上会自动为我生成jquery验证规则: http://blog.codeville.net/2009/01/10/xval-a-validation-framework-for-aspnet-mvc/

    4 回复  |  直到 17 年前
        1
  •  2
  •   Nicholas Head    17 年前

    好的,试试两个。什么是动态添加元素?您不能将.Rules(“add”,)放在同一个代码中吗?

        2
  •  2
  •   phmarco    16 年前

    在live上的鼠标悬停事件似乎已经成功了,假设你没有疯狂使用css:

    // >>> MSG/Comment form validator, now and forever...  
        $('form.streamForms').live('mouseover', function(){
            $(this).validate({
                rules: {
                    text: "required"
    
                },
                messages: {
                    text: " "
                }
            });    
        });
    

    希望有帮助!

        3
  •  0
  •   Nicholas Head    17 年前
        4
  •  0
  •   Ecropolis    15 年前

    我是这样处理的。首先,我创建了验证对象。

        var myvalidations = {};
        myvalidation.registerform = function() { $("#registerform").validate({
                submitHandler: function(form) {
                    $(form).ajaxSubmit(optionspersonal); 
                    //submitReg();
                },
                        rules: {
                    firstname: {
                         required: true,
                         minlength: 5,
                         maxlenght: 22
                    },
                        messages: {
                                 firstname: {
                                     required: "Tell us what to call you by.",
                         minlength: "Your username must consist of at least 5 characters"
                                 }
                         }
                 });
            }
    
    

    现在,无论何时创建表单,都要确保表单上有一个ID或引用它,并在创建后立即调用函数。

        //create my content
        $('.content').html('--fields etc--');
        //add validation
        myvalidation.registerform();
    
    

    欢迎任何进一步的建议;但我认为基本上这是正确的方法。