Javascript 如何在js中的单个函数中验证多个字段

Javascript 如何在js中的单个函数中验证多个字段,javascript,jquery,validation,Javascript,Jquery,Validation,我有一个函数,它需要验证多个文本字段,但似乎无法正确执行。我使用$(“#textfield”).blur(验证)例如,在每个字段失去焦点时运行验证函数(所有三个字段都使用blur调用验证函数)。我想我没有正确地排序if语句。另外,如果您知道使用this进行验证的一种更简单的方法,那也很好。多谢各位 function validation(height,width,color){ if (height.length == 0 || height == null){ //check for emp

我有一个函数,它需要验证多个文本字段,但似乎无法正确执行。我使用
$(“#textfield”).blur(验证)
例如,在每个字段失去焦点时运行验证函数(所有三个字段都使用
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
,然后检查
。长度===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 '';
}

如果(!height){$(“#msg”).text(“height is not defined”)},您也可以使用
。这表示false、undefined、NaN、zero和string空值

您可以简单地使用引导库进行此工作HTML5表单验证帮助您吗?不需要使用脚本。试试看。@Doug问题是我在为考试而学习,我需要这样做。谢谢,我可以在
isNaN
中计算多个变量吗?。像
isNaN(obj1、obj2、obj3)