所以,我正在创建一个使用jQuery validate作为基础的自定义插件。我的想法是创建一个插件,它将验证任何正常形式,而无需为所有这些创建单独的Jquery Validate设置。这是我的代码
HTML
<form role="form" class="form-horizontal form-validate" id="" action="/action/action.users.php">
<div class="box-body">
<h4>Account Information</h4>
<div class="form-group">
<label class="col-sm-3 control-label">test</label>
<div class="col-sm-9 controls">
<div class="row">
<div class="col-xs-12">
<input name="txt_username" class="form-control" placeholder="Username" value="" type="text" data-required="true">
</div>
</div>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">test2</label>
<div class="col-sm-9 controls">
<div class="row">
<div class="col-xs-12">
<input name="txt_password" class="form-control" placeholder="Password" value="" type="text" data-required="true">
</div>
</div>
</div>
</div>
</div>
<div class="box-footer">
<button class="btn btn-sm btn-primary" type="submit">Submit</button>
<button class="btn btn-sm btn-warning" type="reset">Reset</button>
</div>
</form>
js
(function ( $ ) {
$.fn.validate_form = function(options) {
var settings = $.extend({
action: "/",
redirect: "",
notification: "",
}, options
);
var $this = this;
var post_data = {};
var post_response = "default";
/* if first submit, it wont trigger this, succeeding submits, it will run this */
$this.validate({
submitHandler:function(){
$this.find(':input[type="text"],:input[type="radio"],:input[type="password"],:input[type="email"]').each(function(){
element = $(this);
var name = element.attr('name');
var val = element.val();
if(element.is(':radio')) {
if(element.is(':checked'))
post_data[name] = val;
}
else post_data[name] = val;
});
console.log(post_data);
$.post( settings.action, post_data, function(result){
post_response = result;
console.log(result);
});
}
});
/*end if first submit, it wont trigger this */
$this.find('[data-required="true"]').each(function(){
$(this).rules("add",{
required: true
});
});
return post_response;
}
}( jQuery ));
$(document).ready(function() {
$(".form-validate").submit(function(e){
var action = $(this).attr("action");
var result = $(this).validate_form({
action:action
});
e.preventDefault();
});
});
它正在工作,除非,如果表单是第一次提交,验证将不起作用,但是,如果我再次提交,它现在将正常工作。我似乎无法找到问题因为firebug没有错误。任何帮助将不胜感激
答案 0 :(得分:0)
.validate()
方法仅用于 初始化 插件。它不应该包含在.submit()
处理程序中,而且这是解决问题的关键。
仔细阅读此页面以了解基本设置和用法:https://stackoverflow.com/tags/jquery-validate/info