0

I asked my friend what would be the easier to validate a "Phone Number Field" only for numbers and he wrote this. He tried explaining it and "Inverse Logic" yet I didn't understand this code. Can someone explain it to me in the baby infants' terms please?

   function validSet (input, set) {
   for (var i = 0; i < input.length; i++) {
   if (!set.contains(input.charAt(i)) return false;
   }
}

2 Answers2

0

Okay, so essentially what is happening here is that the function validSet is being sent input, which appears to be a character string, and some set or array of values. The for loop is meant to iterate over the characters in the input string and determine if they are present in the provided set which I would assume contains the values 0-9. If the character that input.charAt(i) points to is not contained within the provided set then the function returns false and thus you know the input string is not a valid phone number since it contains some value that is not a digit.

This being said, I would also take this function further to truly check if the value entered is a valid phone number. I.e. make sure it is the correct length and other possible validity checks depending on how much it matters.

Grant P
  • 85
  • 7
0

The function loops through the characters in the input string. For each character in the input string it checks to see if that character exists in the set string. If it doesn't then the input is not valid and false is returned by the function.

For example, if you had: validSet("555-5a55", "0123456789-") the valid test will fail when it gets to the 'a' character because there is no 'a' in the set string.

Phill Treddenick
  • 1,340
  • 13
  • 18
  • Thank you very much :) Does that mean when I call the function in the form as "onSubmit" do I set the value to "onSubmit = "validSet("document.form.textbox.value, 0123456789-");" ? – RidiculousBeans Jun 15 '15 at 22:42
  • I would create another function: `validNumber(input) { return validSet(input, "0123456789-") }` and then call it via: `onSubmit="return validNumber(document.form.textbox.value)"` – Phill Treddenick Jun 16 '15 at 00:55