javascript - 如何在js中的一个函数中验证多个字段

标签 javascript jquery validation

我有一个函数需要验证多个文本字段,但似乎无法正确执行。我用 $("#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/

相关文章:

javascript - Pickadate.js : how to render the widget via another element

java - 如何在 Java 中使用字符堆栈验证 JSON 语法?

javascript - 我的 ng-view 与 index.html 页面 angularjs 无限循环

javascript - TypeScript angularjs 事件绑定(bind)

javascript - Promise.resolve 没有参数

javascript - 使用: string. split ("").reverse().join(")有什么意义?

javascript - 显示 javascript 警报并执行其他操作?

javascript - 如何防止查询字符串值可见

java - 验证可选字段

javascript - 如何在必需和无效时显示不同的消息?