gpt4 book ai didi

jQuery 验证插件 : hide error message and show focussed elements

转载 作者:行者123 更新时间:2023-12-01 07:08:46 25 4
gpt4 key购买 nike

我正在使用 jQuery 验证插件在我的注册表单上进行客户端验证。我想隐藏错误消息“请输入您的名字”并在红色框中显示必填字段。

以下是我的代码:

<script>
$("#register-form").validate({
errorPlacement: function(error, element) {
return true;
}
rules: {
firstname: "required",
lastname: "required"
},
messages: {
firstname: "Please enter your firstname",
lastname: "Please enter your lastname"
}
});
</script>

在这里,我使用了“errorPlacement”选项来隐藏错误消息,但它确实隐藏了消息,但没有聚焦我的必填字段,并且表单也被重新加载。

我希望所有必填字段都集中在红色框中,而不是错误消息

最佳答案

1-隐藏错误消息errorPlacement回调函数设置为return false;而不是return true;

errorPlacement: function(error, element) {
return false;
}, //<---missing comma here

errorPlacement: 函数后缺少 2 个逗号,导致表单提交且不验证输入

3- 验证插件有默认类 errorvalid,修改它们如下以将输入字段突出显示为红色,只需添加 border: 1px Solid red 属性到 error 选择器

.error {
border: 1px solid red;
}
.error:focus {
border: 1px solid red;
}
.valid {
border: 1px solid green;
}

$("#register-form").validate({
errorPlacement: function (error, element) {
return false;
},
rules: {
firstname: "required",
lastname: "required"
},
messages: {
firstname: "Please enter your firstname",
lastname: "Please enter your lastname"
}
});
.error {
border: 1px solid red !important;
}
.error:focus {
border: 1px solid red !important;
}
.valid {
border: 1px solid green !important;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.14.0/jquery.validate.min.js"></script>
<form role="form" id="register-form">
<div class="form-group">
<label for="firstname">FirstName:</label>
<input type="text" class="form-control" name="firstname" id="firstname">
</div>
<div class="form-group">
<label for="lastname">LastName:</label>
<input type="text" class="form-control" name="lastname" id="lastname">
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>

Fiddle

关于jQuery 验证插件 : hide error message and show focussed elements,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33229538/

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