0

I need to validate alpha characters (in a request, node.js) and what i used was:

/[a-zA-Z]+/.test(input)

BUT when a value null was passed, then it was validated OK (regexp returns TRUE) example:

/[a-zA-Z]+/.test(null) // <--- this returns true :(

Somebody can explain me this? i need to avoid nulls, thanks!

mzalazar
  • 6,206
  • 3
  • 34
  • 31

2 Answers2

5

The test() method executes a search for a match between a regular expression and a specified string. Returns true or false

RegExp.prototype.test() converts parameters passed to a String

For example /\d/.test(0) would also return true, as expected, where 0 is a Number passed as parameter.

guest271314
  • 1
  • 15
  • 104
  • 177
2

Because .test() coerces the parameter to a string, you are effectively testing against 'null' - which evaluates to true.

Wayne Allen
  • 1,605
  • 1
  • 10
  • 16