Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate multiple fields in one single function in js

I have a function that needs to validate multiple text fields but cannot seem to get it right. I use $("#textfield").blur(validation); for example, to run the validation function when each field loses focus (all three fields call the validation function using blur). I think i'm not ordering the if statements correctly. Also, if you know a simpler way of doing the validation using this that would be also great. Thank you.

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");
}

}
like image 538
Gonzalo Avatar asked May 28 '26 03:05

Gonzalo


1 Answers

It is advised to check for the null first followed by .length === 0

At the least you can make a reusable isNullOrEmpty function -

   function isNullOrEmpty (obj) {
         return !((obj !== undefined) && (obj !== null) && (obj .length === 0));
    }

Then you can generalize like -

function validateNumber(obj ,fieldName) {
    if(isNaN(obj)) {
        return 'The ' + fieldName + ' must be number.'
    }
    return '';
}
like image 99
Aseem Gautam Avatar answered May 30 '26 16:05

Aseem Gautam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!