我有一个函数需要验证多个文本字段,但似乎无法正确执行。我用 $("#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 '';
}
关于javascript - 如何在js中的一个函数中验证多个字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38189311/