gpt4 book ai didi

javascript - JQuery Validate 插件有效方法总是返回 true

转载 作者:行者123 更新时间:2023-11-30 20:51:57 29 4
gpt4 key购买 nike

好吧,我觉得我太笨了,无法解决这个基本问题,我有一个非常正常的 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()) {
}
});
}();

此函数在验证插件设置其 Angular 色之前执行,将验证 Angular 色移动到在该函数解决我的问题之前执行

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()) {
}
});
}();

最佳答案

首先,没有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()) {
}

关于javascript - JQuery Validate 插件有效方法总是返回 true,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48083538/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com