基於Bootstrap jQuery.validate Form表單驗證明踐
項目結構 :
github 上源碼地址:https://github.com/starzou/front-end-example
點擊打開
一、form 表單代碼
須要引用 jquery.js,bootstrap.js,jquery.validate.js 庫
二、form.js 代碼
- var MyValidator = function() {
- var handleSubmit = function() {
- $('.form-horizontal').validate({
- errorElement : 'span',
- errorClass : 'help-block',
- focusInvalid : false,
- rules : {
- name : {
- required : true
- },
- password : {
- required : true
- },
- intro : {
- required : true
- }
- },
- messages : {
- name : {
- required : "Username is required."
- },
- password : {
- required : "Password is required."
- },
- intro : {
- required : "Intro is required."
- }
- },
-
- highlight : function(element) {
- $(element).closest('.form-group').addClass('has-error');
- },
-
- success : function(label) {
- label.closest('.form-group').removeClass('has-error');
- label.remove();
- },
-
- errorPlacement : function(error, element) {
- element.parent('div').append(error);
- },
-
- submitHandler : function(form) {
- form.submit();
- }
- });
-
- $('.form-horizontal input').keypress(function(e) {
- if (e.which == 13) {
- if ($('.form-horizontal').validate().form()) {
- $('.form-horizontal').submit();
- }
- return false;
- }
- });
- }
- return {
- init : function() {
- handleSubmit();
- }
- };
-
- }();
效果 :