javascript 如何使用 jQuery 在字段旁边添加验证错误消息
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18263385/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to add a validation error message next to a field using jQuery
提问by Amarundo
Hi have a form with a few fields. Amongst them:
嗨,有一个包含几个字段的表单。其中:
<div>
<label for="phoneNumber" class="label">Phone Number</label>
<input name="phoneNumber" type="text" id="phoneNumber" size="13" style="float:left;margin-right:10px;">
</div>
<div>
<input type="checkbox" name="activePN" id="activePN" checked >
<label for="activePN">Active</label>
</div>
The, when the form is submited, I want to validate the input and write next to each field for whichever field didn't validate. Like this:
提交表单时,我想验证输入并在每个字段旁边写入未验证的字段。像这样:
$('#submit').click(function () {
var proceed = true;
var strippedPN = $('#phoneNumber').val().replace(/[^\d\.]/g, '').toString(); //strips non-digits from the string
if (strippedPN.length !== 10) {
$('#phoneNumber').text('<p>Phone number has to be 10 digits long.</p>')
proceed = false;
}
...
...
...
});
I was hopping that adding those <p> </p>
tags would do it. But they don't...
Note: I also tried with html()
instead of text()
and with activePN
instead of phoneNumber
.
我希望添加这些<p> </p>
标签会做到这一点。但他们没有... 注意:我也试过用html()
代替text()
和用activePN
代替phoneNumber
。
回答by Grim...
Use .after()
.
使用.after()
.
$('#phoneNumber').after('<p>Phone number has to be 10 digits long.</p>')
It might be wise to add a class to your p
tag too, so you can remove them when the number is edited to be correct.
将一个类添加到您的p
标签也可能是明智的,这样您就可以在将数字编辑为正确时删除它们。
回答by StackSlave
Try:
尝试:
$('#submit').click(function(){
var proceed = true;
var strippedPN = $('#phoneNumber').val().replace(/[^\d\.]/g, ''); //strips non-digits from the string - already a String
if(strippedPN.length !== 10){
$('#phoneNumber').after('<p>Phone number has to be 10 digits long.</p>')
proceed = false;
}
}
回答by shaijut
Its best to use jqueryvalidationplugin.
最好使用jqueryvalidation插件。
But in some scenario may be you need to show validation message using custom code, then below may help.
但在某些情况下,您可能需要使用自定义代码显示验证消息,那么下面可能会有所帮助。
Code
代码
var errorSeen = false;
$('#txtname').keyup(function (e) {
var validInput = false; // TODO set your validation here
if (!validInput) {
var errorMessageVisible = $(".validationMessage").is(":visible");
if (errorSeen === false && errorMessageVisible === false) {
$('#txtname').style.borderColor = "red";
$('#txtname').after("<span class='validationMessage' style='color:red;'>
Name is required.</span>");
errorSeen = true;
}
}
else {
$('#txtname').style.borderColor = "";
var errorMessageVisible = $(".validationMessage").is(":visible");
if (errorMessageVisible)
$(".validationMessage").remove();
errorSeen = false;
}
});