-1

I am building a Js function with Jquery checking if certain inputs are empty or not for validation. Here's the function that checks if the inputs are empty or not:

   function isValid(elements){
      var validation = false
      elements.each(function() {
        if ($( this ).val().length > 0){
          validation = true
        }
        else {
          validation
        }
      });
      validation
    }

however whatever I do my function returns undefined and never the boolean value that is supposed to be contained in the validation variable ?

What should I do for my function to return true or false ?

4
  • What are you passing into for elements? Commented Jul 26, 2016 at 15:37
  • 3
    You are not at all returning anything from the function. Commented Jul 26, 2016 at 15:37
  • What do you think validation lines are doing? Your logic is also flawed. The validation is most likely not doing what you want it to do. Commented Jul 26, 2016 at 15:53
  • indeed I thought the my last validation was returning my boolean value but now I understand I need to use return Commented Jul 26, 2016 at 17:05

3 Answers 3

2

You can return false if at least one element is empty, otherwise return true.

function isValid(elements){
  var validation = true;

  elements.each(function() {
    if ($( this ).val().trim().length === 0){
      validation = false;
    }
  });

  return validation;
}
Sign up to request clarification or add additional context in comments.

2 Comments

return false inside of each would act as a breaking statement
You may also want to add a trim() in the length check, otherwise filling the field with spaces would be valid
2

You can do your code like below by using Array#some,

function isValid(elements) {
 return !Array.from(elements).some(function(itm){ itm.value.trim().length == 0 });
}

You are not at all returning anything from the function, that means as a default returning value undefined will be returned.

Comments

2

Your function isValid() is returning undefined because this is the expected behaviour in JavaScript: undefined is the “default” returned value if a function does not specify one returned value, and your function isValid() doesn't have any return.

Check this answer.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.