Javascript检查验证并更改文本框颜色 [英] Javascript to check validation and change textbox color
问题描述
查看代码:
<script type="text/javascript">
function ValidateTextBox(source, args) {
var is_valid = false;
//Regex goes here
var regex = /^[a-z A-Z]+$/;
var check = regex.test($('tbName').val()); //Checks the tbName value against the regex
if (check == true) {
//If input was correct
is_valid = true;
}
else {
//If input is not correct
$("tbName").css(("background-color", "#A00000"), ("border-color", "#780000"));
}
args.IsValid = is_valid; //Returns validity state
}
</script>
我正在尝试检查文本框的输入,以便其唯一的字符介于a和z之间,以及A和Z之间,但即使在输入"1245"时,它仍然返回true.
这是为什么?
谢谢
$('tbName')
可能不是有效的选择器.
您是要选择一个班级吗?
$(.tbName')
一个id = tbName
的元素呢?
$('#tbName')
此外,您为什么需要这样做?这是在函数外部无法访问的,因为它是传递给函数的局部变量(通过其参数)
args.IsValid = is_valid;
您可以进行简单的退货:
function ValidateTextBox() {
var regex = /^[a-z A-Z]+$/;
return regex.test($('#tbName').val());
}
Check out the code:
<script type="text/javascript">
function ValidateTextBox(source, args) {
var is_valid = false;
//Regex goes here
var regex = /^[a-z A-Z]+$/;
var check = regex.test($('tbName').val()); //Checks the tbName value against the regex
if (check == true) {
//If input was correct
is_valid = true;
}
else {
//If input is not correct
$("tbName").css(("background-color", "#A00000"), ("border-color", "#780000"));
}
args.IsValid = is_valid; //Returns validity state
}
</script>
Im trying to check the input of a textbox so its only character between a and z, and A and Z, but it still returns true even on input like "1245".
Why is this?
Thanks
$('tbName')
may not be a valid selector.
Did you mean to select a class?
$(.tbName')
What about an element with an id=tbName
?
$('#tbName')
Also, why do you need to do this? This will NOT be accessible outside of the function, as it is a local variable passed to the function (via its parameters)
args.IsValid = is_valid;
You can just do a simple return:
function ValidateTextBox() {
var regex = /^[a-z A-Z]+$/;
return regex.test($('#tbName').val());
}
这篇关于Javascript检查验证并更改文本框颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!