执行验证时出现jQuery问题

时间:2014-01-10 15:50:21

标签: javascript jquery jquery-validate

我正在尝试使用jQuery验证文件进行表单验证。这让我很难过...... 这是一个简单的表单,我现在正在做的是检查用户名是否输入:

  • 无法以数字开头
  • 不能只是数字
  • 无法以符号开头
  • 不能只是符号
  • 应该是这样的例子:username = panchi15_或jack或a77

这是html片段:

  <div class="row-fluid">
      <div class="span6 ">
        <div class="control-group">
          <label class="control-label">Usuario<span class="required">*</span></label>
          <div class="controls">
          <input type="text" name="username" value="" class="m-wrap span8" required/>
        </div>
      </div>
  </div>

在这个文件的顶部我正在调用以下文件:

<script type="text/javascript" src="{site_url()}assets/plugins/jquery-validation/dist/jquery.validate.min.js"></script>
<script type="text/javascript" src="{site_url()}assets/plugins/jquery-validation/dist/additional-methods.js"></script>

我的js文件:

var FormValidation = function () {

var handleValidation2 = function() {
    // for more info visit the official plugin documentation: 
    // http://docs.jquery.com/Plugins/Validation

        var form2 = $('#form-val');
        var error2 = $('.alert-error', form2);
        var success2 = $('.alert-success', form2);

        //IMPORTANT: update CKEDITOR textarea with actual content before submit
        form2.on('submit', function() {
            for(var instanceName in CKEDITOR.instances) {
                CKEDITOR.instances[instanceName].updateElement();
            }
        })

        form2.validate({
            errorElement: 'span', //default input error message container
            errorClass: 'help-inline', // default input error message class
            focusInvalid: false, // do not focus the last invalid input
            ignore: "",
            rules: {
                //utilizo el plugin additional-methods.js para crear algunas reglas y validar
                username: {
                    minlength: 2,
                    maxlength: 15,
                    // pattern: "[a-zA-Z0-9]*[a-zA-Z]+[a-zA-Z0-9]*",
                    //el nombre de usuario no puede empezar con numeros
                    // pattern: "/^!=.*\d\w{2,15}$/",
                    pattern: true,
                    required: true

                },

                name: {
                    minlength: 2,
                    maxlength: 50,
                    // regex: ,
                    required: true
                },

                lastname: {
                    minlength: 2,
                    maxlength: 50,
                    required: true
                },

                gender: {
                    required: true
                },

                date_born: {
                    required: true
                },

                email: {
                    required: true,
                    email: true
                },

                status: {
                    required: true
                },

                member_id: {
                    minlength: 5,
                },

                documentType_id: {
                    required: true
                },

                documentn: {
                    required: true,
                    minlength: 2
                },
                address_street: {
                    required: true
                },

                address_number: {
                    required: true
                },

                address_floor: {
                    required: false
                },

                zipcode: {
                    required: true
                },

                city: {
                    required: true
                },

                state: {
                    required: true
                },

                country_id: {
                    required: true
                },

                phone: {
                    required: true
                },

                cellphoneNumber: {
                    required: true
                },

                cellCompany: {
                    required: true
                },

                cellbrand: {
                    required: true
                },

                marital_status: {
                    required: true
                },

                sons: {
                    required: true
                },
            },

            messages: { // custom messages for radio buttons and checkboxes
                username: {
                    // required: "Este campo es requerido",
                    minlength: "Mínimo 2 caracteres",
                    maxlength: "Máximo 15 caracteres",  
                    // remote: "No Disponible"

                },

                membership: {
                    required: "Please select a Membership type"
                },
                service: {
                    required: "Please select  at least 2 types of Service",
                    minlength: jQuery.format("Please select  at least {0} types of Service")
                }
            },

            // errorPlacement: function (error, element) { // render error placement for each input type
            //     if (element.attr("name") == "education") { // for chosen elements, need to insert the error after the chosen container
            //         error.insertAfter("#form_2_education_chzn");
            //     } else if (element.attr("name") == "membership") { // for uniform radio buttons, insert the after the given container
            //         error.addClass("no-left-padding").insertAfter("#form_2_membership_error");
            //     } else if (element.attr("name") == "editor1" || element.attr("name") == "editor2") { // for wysiwyg editors
            //         error.insertAfter($(element.attr('data-error-container'))); 
            //     } else if (element.attr("name") == "service") { // for uniform checkboxes, insert the after the given container
            //         error.addClass("no-left-padding").insertAfter("#form_2_service_error");
            //     } else {
            //         error.insertAfter(element); // for other inputs, just perform default behavior
            //     }
            // },

            invalidHandler: function (event, validator) { //display error alert on form submit   
                success2.hide();
                error2.show();
                App.scrollTo(error2, -200);
            },

            highlight: function (element) { // hightlight error inputs
                $(element)
                    .closest('.help-inline').removeClass('ok'); // display OK icon
                $(element)
                    .closest('.control-group').removeClass('success').addClass('error'); // set error class to the control group
            },

            unhighlight: function (element) { // revert the change done by hightlight
                $(element)
                    .closest('.control-group').removeClass('error'); // set error class to the control group
            },

            success: function (label) {
                if (label.attr("for") == "service" || label.attr("for") == "membership") { // for checkboxes and radio buttons, no need to show OK icon
                    label
                        .closest('.control-group').removeClass('error').addClass('success');
                    label.remove(); // remove error label here
                } else { // display success icon for other inputs
                    label
                        .addClass('valid').addClass('help-inline ok') // mark the current input as valid and display OK icon
                    .closest('.control-group').removeClass('error').addClass('success'); // set success class to the control group
                }
            },

            submitHandler: function (form) {
                success2.show();
                error2.hide();
            }

        });

        // $('#form-val').select2({
        //     placeholder: "Select an Option",
        //     allowClear: true
        // });

        // //apply validation on chosen dropdown value change, this only needed for chosen dropdown integration.
        // $('.chosen, .chosen-with-diselect', form2).change(function () {
        //     form2.validate().element($(this)); //revalidate the chosen dropdown value and show error or success message for the input
        // });

        //  //apply validation on select2 dropdown value change, this only needed for chosen dropdown integration.
        // $('.select2', form2).change(function () {
        //     form2.validate().element($(this)); //revalidate the chosen dropdown value and show error or success message for the input
        // });
}

return {
    // main function to initiate the module
    init: function () {           
        handleValidation2();
    }
};
}();

如果用户输入有效的用户名,则输入旁边应显示绿色的ok图标。否则输入框应为红色,并带有一个图例,告知错误是什么。

我做错了什么?

更新: http://jsfiddle.net/jimena/wXm3p/

1 个答案:

答案 0 :(得分:0)

如果将来有人需要,我会回答我的问题。我可以找出我做错了什么。

在其中一个jQuery验证文件additional-methods.js中,有一个与word模式相关的函数:

jQuery.validator.addMethod("pattern", function(value, element, param) {
if (this.optional(element)) {
    return true;
}
if (typeof param === 'string') {
    param = new RegExp('^(?:' + param + ')$');
}
return param.test(value);
 }, "Invalid format.");

正如您所看到的,它接收3个参数,值,元素和参数。 Param是您定义的正则表达式,用于匹配代码行中已有的预定义元素:

param = new RegExp('^(?:' + param + ')$');

在我创建的js文件中,您可以在我的问题上看到,仅使用它:

   pattern: "[A-z](([\._\-][A-z0-9])|[A-z0-9])*[a-z0-9_]*"

是的,就是这样。