I have this RegEx that validates input (in javascript) to make sure user didn't enter more 开发者_运维问答than 1000 characters in a textbox:
^.{0,1000}$
It works ok if you enter text in one line, but once you hit Enter and add new line, it stops matching. How should I change this RegEx to fix that problem?
The problem is that .
doesn't match the newline character. I suppose you could use something like this:
^[.\r\n]{0,1000}$
It should work (as long as you're not using m
), but do you really need a regular expression here? Why not just use the .length
property?
Obligatory jwz quote:
Some people, when confronted with a problem, think "I know, I'll use regular expressions." Now they have two problems.
Edit: You could use a CustomValidator
to check the length instead of using Regex. MSDN has an example available here.
What you wish is this:
/^[\s\S]{0,1000}$/
The reason is that .
won't match newlines.
A better way however is to not use regular expressions and just use <text area element>.value.length
If you just want to verify the length of the input wouldn't it be easier to just verify the length of the string?
if (input.length > 1000)
// fail validation
精彩评论