jQuery验证插件,在Twitter Bootstrap本机元素中放置错误

前端之家收集整理的这篇文章主要介绍了jQuery验证插件,在Twitter Bootstrap本机元素中放置错误前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在使用Twitter Boostrap,并尝试将jQuery验证插件错误放在正确的元素中,而不是在 HTML中硬编码的每个消息.

请看这里的jsfiddle:http://jsfiddle.net/yaEaF/1/

$('#register').validate({
rules: {
    name: {
        minlength: 2,required: true
    },lname: {
        minlength: 2,username: {
        minlength: 2,required: true,remote: {
            url: '/setup/verify_username/',cache: false
        }
    },email: {
        required: true,email: true,remote: {
            url: '/setup/verify_email/',password: {
        required: true,minlength: 5,maxlength: 250
    },password2: {
        equalTo: '#password'
    },postal_code: {
        required: true,minlength: 5
    },timezones: {
        required: true
    },mp: {
        minlength: 10,gender: {
        required: true
    },dob: {
        required: true,date: true
    }
},messages: {
    name: "Please enter your first name",lname: "Please enter your last name",username: {
        required: "Please enter a username",minlength: "Your username must consist of at least 2 characters"
    },email: "Please enter a valid email address",password: {
        required: "Please provide a password",minlength: "Your password must be at least 5 characters long"
    },password2: {
        required: "Please provide a password",minlength: "Your password must be at least 5 characters long",equalTo: "Please enter the same passwords"
    },postal_code: "Please enter a valid zip code",timezones: "Please select a time zone",mp: "Please enter a valid mobile number. Only numbers please.",gender: "Please select a gender",dob: "Please enter a valid Date of Birth in mm/dd/yyyy format."
},highlight: function (element,errorClass,validClass) {
    $(element).closest('.control-group').removeClass('success').addClass('error');
},unhighlight: function (element,validClass) {
    $(element).closest('.control-group').removeClass('error').addClass('success');
},success: function (label) {
    $(label).closest('form').find('.valid').removeClass("invalid");
},errorPlacement: function (error,element) {
    error.text(element.closest('.control-group').find('.help-block'));
}
});

解决方法

首先,从你的内联代码中清空所有的消息,但是由于我们不想太多地破坏你的布局,所以将它放在原处.
<span class="help-block"></span>

然后修改您的errorPlacement回调如下:

errorPlacement: function (error,element) {
    element.closest('.control-group').find('.help-block').html(error.text());
}

现在,将使用.validate()中定义的所有消息.注意我如何用自动占位符{0}替换规则的值.

messages: {
    name: "Please enter your first name",minlength: "Your username must consist of at least {0} characters"
    },minlength: "Your password must be at least {0} characters long",maxlength: "Your password must be less than {0} characters long"
    },password2: {
        equalTo: "Please enter the same passwords"
    },

工作演示:http://jsfiddle.net/yaEaF/6/

原文链接:https://www.f2er.com/jquery/175781.html

猜你在找的jQuery相关文章