1 $('#defaultForm').bootstrapValidator({ 2 message: 'This value is not valid', 3 feedbackIcons: { 4 valid: 'glyphicon glyphicon-ok', 5 invalid: 'glyphicon glyphicon-remove', 6 validating: 'glyphicon glyphicon-refresh' 7 }, 8 fields: { 9 acGroupName: { 10 validators: { 11 notEmpty: { 12 message: '用戶組名不能為空' 13 }, 14 stringLength: { 15 max: 30, 16 message: '用戶組名過長' 17 }, 18 remote: { 19 url: "<%=basePath%>/accountGroup/existAccountRepeat", 20 message: '用戶組名已存在', 21 data:{id:function(){ 22 return $("#defaultForm input[name='id']").val(); 23 }} 24 } 25 26 } 27 }, 28 acGroupContent: { 29 validators:{ 30 notEmpty: { 31 message: '用戶組信息不能為空' 32 }, 33 } 34 }, 35 strategyGroupId: { 36 validators:{ 37 notEmpty: { 38 message: '策略組不能為空' 39 }, 40 } 41 }, 42 } 43 }).on('success.form.bv', function(e) { 44 if(againSubmit){ 45 return ; 46 } 47 againSubmit = true; 48 // 終止重復提交 49 e.preventDefault(); 50 // 得到form表單對象 51 var $form = $(e.target); 52 // 獲得bootstrap驗證對象 53 var bv = $form.data('bootstrapValidator'); 54 // 使用Ajax提交form表單數據 55 $.post($form.attr('action'), $form.serialize(), function(result) { 56 if(result=='1'){ 57 window.top.layer.alert('保存成功!', {icon: 6, title:"提示"},function(index){ 58 window.top.layer.close(index); 59 closeLayer(); 60 }); 61 }else{ 62 parent.layer.alert("保存失敗!", {title:"提示"}); 63 againSubmit = false; 64 } 65 }, 'json'); 66 });
可以看到remote那里有一個ajax驗證重名,效果是bootstrapValidator沒有等ajax拿到返回值就直接拿了一個默認值false走人了。所以自動提交方式弊端很大 經過修改,如下:即可成功
1 $('#defaultForm').bootstrapValidator({ 2 message: 'This value is not valid', 3 feedbackIcons: { 4 valid: 'glyphicon glyphicon-ok', 5 invalid: 'glyphicon glyphicon-remove', 6 validating: 'glyphicon glyphicon-refresh' 7 }, 8 fields: { 9 acGroupName: { 10 validators: { 11 notEmpty: { 12 message: '用戶組名不能為空' 13 }, 14 stringLength: { 15 max: 30, 16 message: '用戶組名過長' 17 }, 18 remote: { 19 url: "<%=basePath%>/accountGroup/existAccountRepeat", 20 message: '用戶組名已存在', 21 data:{id:function(){ 22 return $("#defaultForm input[name='id']").val(); 23 }} 24 } 25 26 } 27 }, 28 acGroupContent: { 29 validators:{ 30 notEmpty: { 31 message: '用戶組信息不能為空' 32 }, 33 } 34 }, 35 strategyGroupId: { 36 validators:{ 37 notEmpty: { 38 message: '策略組不能為空' 39 }, 40 } 41 }, 42 } 43 }); 44 $('#defaultForm').submit(function(){ 45 var flag = $('#defaultForm').data("bootstrapValidator").isValid(); 46 setTimeout(function(){ 47 var flag2 = $('#defaultForm').data("bootstrapValidator").isValid(); 48 if(flag2){ 49 var $form = $('#defaultForm'); 50 // 使用Ajax提交form表單數據 51 $.post($form.attr('action'), $form.serialize(), function(result) { 52 if(result=='1'){ 53 window.top.layer.alert('保存成功!', {icon: 6, title:"提示"},function(index){ 54 window.top.layer.close(index); 55 closeLayer(); 56 }); 57 }else{ 58 parent.layer.alert("保存失敗!", {title:"提示"}); 59 againSubmit = false; 60 } 61 }, 'json'); 62 } 63 }, 500); 64 });
可以看到,我不用自動提交 我通過一個延時處理等待ajax返回值即可。