How to escape a RegEx that generates an error of “

2019-06-24 08:23发布

I use asp.net and C#. I have TextBox with an Validation Control with RegEx.

I use this code as validation.

ValidationExpression="^(?s)(.){4,128}$"

But only in IE9 I receive an error: unexpected quantifier from the javascript section.

Probably I have to escape my RegEx but I do not have any idea how to do it and what to escape.

Could you help me with a sample of code? Thanks

3条回答
仙女界的扛把子
2楼-- · 2019-06-24 08:52

Three problems: (1) JavaScript doesn't support inline modifiers like (?s), (2) there's no other way to pass modifiers in an ASP validator, and (3) neither of those facts matters, because JavaScript doesn't support single-line mode. Most people use [\s\S] to match anything-including-newlines in JavaScript regexes.

EDIT: Here's how it would look in your case:

ValidationExpression="^[\s\S]{4,128}$"

[\s\S] is a character class that matches any whitespace character (\s) or any character that's not a whitespace character--in other words, any character. The dot (.) metacharacter matches any character except a newline. Most regex flavors (like .NET's) support a "Singleline" or "DOTALL" mode that makes the dot match newlines, too, but not JavaScript.

查看更多
放荡不羁爱自由
3楼-- · 2019-06-24 09:02

Write it like this instead :

 ^([\s\S]){4,128}$

I suspect that (?s) is the cause of the error.

查看更多
迷人小祖宗
4楼-- · 2019-06-24 09:07

JavaScript doesn't understand (?s) afaik, instead you can replace . with [^] or [\s\S].

Eg: ^[^]{4,128}$

查看更多
登录 后发表回答