好的我觉得我太过倾向于解决这个基本问题,我有一个非常普通的Html表单:
<form id="SimpleForm" class="form-horizontal bordered-row">
<div class="form-group">
<label class="col-sm-3 control-label">Service provider</label>
<div class="col-sm-6">
<input type="text" class="form-control required" id="pname" name="pname" data-val="true">
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Store name</label>
<div class="col-sm-6">
<input type="text" class="form-control required" id="storeName" data-val="true" name="storeName" placeholder="">
</div>
</div>
</form>
和一个JQuery验证函数
var $ValidateForm = $("#SimpleForm").validate({
roles: {
pname: {
required: true,
//minlength: 5,
//maxlength: 50
},
storeName: {
required: true,
//minlength: 5,
//maxlength: 50
}
},
messages: {
pname: {
required: "Required field"
},
storeName: {
required: "Required field"
}
},
errorElement: 'div',
errorLabelContainer: '.alert-danger',
errorPlacement: function (error, element) {
var placement = $(element).data('error');
if (placement) {
$(placement).append(error);
} else {
error.insertAfter(element);
}
}
});
//Always true !!
if ($ValidateForm.valid()) {
}
这是一个非常基本的东西,仍然无法正常工作,请在失去更多头发之前帮忙!
修改:
我忘记提到我有一个自我执行功能,他是罪魁祸首:
var postSp = function () {
$("#BtnAddProvider").click(function (e) {
if ($ValidateForm.valid()) {
}
});
}();
此功能在验证插件设置其角色之前执行,在该功能解决我的问题之前将验证角色移至执行
var postSp = function () {
$("#SimpleForm").validate({
roles: {
pname: {
required: true,
//minlength: 5,
//maxlength: 50
},
storeName: {
required: true,
//minlength: 5,
//maxlength: 50
}
},
messages: {
pname: {
required: "Required field"
},
storeName: {
required: "Required field"
}
},
errorElement: 'div',
errorLabelContainer: '.alert-danger',
errorPlacement: function (error, element) {
var placement = $(element).data('error');
if (placement) {
$(placement).append(error);
} else {
error.insertAfter(element);
}
}
});
$("#BtnAddProvider").click(function (e) {
if ($ValidateForm.valid()) {
}
});
}();
答案 0 :(得分:1)
首先,没有id为#CreateForm
的表单元素。它应该是#SimpleForm
$("#SimpleForm").validate({
roles: {
pname: {
required: true,
//minlength: 5,
//maxlength: 50
},
storeName: {
required: true,
//minlength: 5,
//maxlength: 50
}
},
messages: {
pname: {
required: "Required field"
},
storeName: {
required: "Required field"
}
},
errorElement: 'div',
errorLabelContainer: '.alert-danger',
errorPlacement: function (error, element) {
var placement = $(element).data('error');
if (placement) {
$(placement).append(error);
} else {
error.insertAfter(element);
}
}
});
然后你不应该使用从validate
返回的变量,只是尝试这样;
if ($("#SimpleForm").valid()) {
}