jquery正则表达式验证错误

时间:2014-01-07 20:36:49

标签: javascript jquery regex codeigniter

我是编程新手。我正在尝试验证表单。我用php(我使用的是Codeigniter)并没有问题,工作正常。

说到jquery,我遇到了麻烦。例如,对于用户名,如果输入验证,它应该显示为ok图标。为此,我就是这样:

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: {

                username: {
                    minlength: 2,
                    maxlength: 15,
                    regex: "^[a-zA-Z0-9]*[a-zA-Z]+[a-zA-Z0-9]*$",
                    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: "El nombre de usuario debe tener como mínimo 2 caracteres",
                    maxlength: "El nombre de usuario debe tener como máximo 15 caracteres",  
                },

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

这是完整的代码,尚未完成更改。问题是如果输入小于2个字符或大于15,则会出现错误,但是当输入正确时,图标确定不会出现,并在检查时出现以下错误:

未捕获的TypeError:无法调用未定义的方法'call'

如果我删除规则“正则表达式”图标确定出现。但正如您在片段中看到的那样,使用该字段时效果不佳。

问题是什么? thnx提前。

2 个答案:

答案 0 :(得分:2)

如果你想在不编写自定义方法的情况下匹配正则表达式(如Hayzeus' s),请加载jquery-validate其他方法:

<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/additional-methods.min.js"></script>

然后您可以使用pattern验证方法:

            username: {
                minlength: 2,
                maxlength: 15,
                pattern: "[a-zA-Z0-9]*[a-zA-Z]+[a-zA-Z0-9]*",
                required: true
            },

该方法会自动使用^$包装模式,因此您在正则表达式中不需要它们。

答案 1 :(得分:1)

您不能简单地在规则中提供正则表达式字符串。您需要向验证器添加自定义方法。

这样的事情:

$.validator.addMethod("regex", function(value, element) {
    var regex = /^[a-zA-Z0-9]*[a-zA-Z]+[a-zA-Z0-9]*$/
    return regex.test(value);
}, "Invalid Name");

然后在你的规则中:

username: {
    minlength: 2,
    maxlength: 15,
    regex: true,
    required: true
}