在jquery中创建一个验证表单

时间:2016-04-19 08:02:59

标签: jquery

验证用户名和密码的函数或方法有多少种?

我尝试了一些代码但无法理解。所有代码都彼此不同。

此代码有效

<script type="text/javascript">
    $(document).ready(function() {

        $.validator.addMethod("email", function(value, element) {
            return this.optional(element) || /^[a-zA-Z0-9._-]+@[a-zA-Z0-9-]+\.[a-zA-Z.]{2,5}$/i.test(value);
        }, "Please enter a valid email address.");

        $.validator.addMethod("username", function(value, element) {
            return this.optional(element) || /^[a-zA-Z0-9._-]{3,16}$/i.test(value);
        }, "Username are 3-15 characters");


        $.validator.addMethod("password", function(value, element) {
            return this.optional(element) || /^[A-Za-z0-9!@#$%^&*()_]{6,16}$/i.test(value);
        }, "Passwords are 6-16 characters");



        // Validate signup form
        $("#signup").validate({
            rules: {
                email: "required email",
                username: "required username",
                password: "required password",

            },


        });

    });
</script>

但这不起作用:

<script type="text/javascript">
    (function($, W, D) {
        var JQUERY4U = {};

        JQUERY4U.UTIL = {
            setupFormValidation: function() {
                //form validation rules
                $("#register-form").validate({
                    rules: {
                        firstname: "required",
                        lastname: "required",
                        email: {
                            required: true,
                            email: true
                        },
                        password: {
                            required: true,
                            minlength: 5
                        },
                        agree: "required"
                    },
                    messages: {
                        firstname: "Please enter your firstname",
                        lastname: "Please enter your lastname",
                        password: {
                            required: "Please provide a password",
                            minlength: "Your password must be at least 5 characters long"
                        },
                        email: "Please enter a valid email address",
                        agree: "Please accept our policy"
                    },
                    submitHandler: function(form) {
                        form.submit();
                    }
                });
            }
        }

        //when the dom has loaded setup form validation rules
        $(D).ready(function($) {
            JQUERY4U.UTIL.setupFormValidation();
        });

    })(jQuery, window, document);
</script>

他们之间有什么区别?

0 个答案:

没有答案