2

I need to verify that an input is between 1 and 512 characters long. I'm using the standard length-check regex of /^.{1,512}$/. When I run

/^.{1,512}$/.test(null)

it returns true. How do I get a length-check regex to fail against null? And why does this test true against null in the first place?

EDIT: Leaving this here since it's more googleable in my case than the earlier question, but per here, the problem is that the regex coerces null into 'null' before testing.

Community
  • 1
  • 1
Dave
  • 487
  • 2
  • 12
  • 1
    what should this do for other types, e.g. `123.345`, `false`, `{foo:1}` etc? – georg Jun 27 '13 at 14:33
  • @epascarello is right, that answers my question - null was being coerced into 'null'. THANK YOU! – Dave Jun 27 '13 at 14:37

1 Answers1

0

I would test with a regex like this:

var myregexp = /^(?!null).{1,512}$/m;;
Lorenzo Persichetti
  • 1,480
  • 15
  • 24
  • 1
    This relies on maybe-detecting coercion after the fact – it would fail if fed "null", which is a four-character string and should pass. Fine for my uses though, as "null" isn't a valid value for my field for other reasons! – Dave Jun 27 '13 at 21:10