开发者

Regex to allow text, some special characters and keep below a specified length

I'm trying to create a validation expression that checks the length of an input and allows text and punctuation marks (e.g. , ? ; : ! " £ $ % )

What I have come up with so far is "^\s*(\w\s*){1,2046}\s*$" but this won't allow any punctuation marks. To be honest I'm pr开发者_JS百科etty sketchy in this area so any help would be greatly appreciated!

Thanks,

Steve


^[\w\s.,:;!?€¥£¢$-]{0,2048}$

^ -- Beginning of string/line
[] -- A character class
\w -- A word character
\s -- A space character
.,:;!?€¥£¢$- -- Punctuation and special characters
{} -- Number of repeats (min,max)
$ -- End of string/line


If you're looking to allow text and punctuation what are you looking to exclude? Digits? \D will give you everything that isn't a digit


You may already know this, but: guarding against malicious input should be handled server side, not in form validation on the client side. Black hats won't bat an eye at bypassing your script.

I think with most popular web front end frameworks there is library code for scrubbing input. A short regex alone is fairly flimsy for guarding against a SQL injection attack.


This should do it:

^\s*([\w,\?;:!"£$%]\s*){1,2046}$

Note that this doesn't limit the length of the input at all, it only limits the number of non-white-space characters.

To limit the length, you can use a positive lookahead that only matches a specific length range:

^(?=.{1,2046}$)\s*([\w,\?;:!"£$%]\s*)+$

(The upper limit on the number of non-white-space characters is pointless if it's the same as the length. The + is short for {1,}, requiring at least one non-white-space character.)


This regular expression should match all your characters and limit the input:

^\s*([\w\s\?\;\:\!\"£\$%]{1,2046})\s*$
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜