[英]How to validate multiple fields in one single function in js
我有一个功能,需要验证多个文本字段,但似乎无法正确。 我用$("#textfield").blur(validation);
例如,在每个字段失去焦点时运行验证功能(所有三个字段都使用blur
调用验证功能)。 我想我不是正确地命令if
语句。 此外,如果您知道使用this
方法进行验证的更简单方法,那也很棒。 谢谢。
function validation(height,width,color){
if (height.length == 0 || height == null){ //check for empty field
$("#msg").html("This field cannot be empty");
}
else if (isNaN(height)){ //check that height is a number
$("#msg").html("The height must be a number");
}else{
$("#msg").html("The height is " + height); //if height is ok shows this message
}
if (width.length == 0 || width== null){ //same for width
$("#msg").html("This field cannot be empty");
}
else if (isNaN(width)){
$("#msg").html("The width must be a number");
}else{
$("#msg").html("The width is " + width);
}
if (color.length == 0 || color == null){
$("#msg").html("This field cannot be empty");
}
else if (color == "white" || color == "grey"){ //check that color is one of these two options
$("#msg").html("The color is " + color);
}else{
$("#msg").html("The color must be white or grey");
}
}
建议首先检查null
然后检查.length === 0
至少你可以制作一个可重用的isNullOrEmpty
函数 -
function isNullOrEmpty (obj) {
return !((obj !== undefined) && (obj !== null) && (obj .length === 0));
}
然后你可以概括如下 -
function validateNumber(obj ,fieldName) {
if(isNaN(obj)) {
return 'The ' + fieldName + ' must be number.'
}
return '';
}
你也可以使用if(!height) { $("#msg").text("Height is not defined") }
。这代表false,undefined,NaN,零和字符串空值
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.