URL 验证 MVC razor 和 JQuery 的问题
我正在研究 MVC Razor。我遇到验证 URL 验证的问题。
我需要在插入临时数据库之前进行 URL 验证。
我得到了 http: //www.regxlib.com/Search.aspx?k=&c=2&m=-1&ps=20
并找到了一种很好的验证模式,
(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?
当我在 MVC 视图中工作时,它给了我错误,所以我在运行时将其更改为
(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@@?^=%&:/~\+#]*[\w\-\@@?^=%&/~\+#])?
ie
@@
而不是 @
,如果我看到控制台,我得到了原始控制台,所以我认为这是可以的我要做 @@
而不是 @
但在控制台中我收到错误
谁能告诉我这有什么问题,所以得到了错误,
“字符类中的范围无效”
I am working on MVC Razor. I face an issue to validate URL validation.
I need to do URL validation before inserting in temp DB.
I got a reference of http://www.regxlib.com/Search.aspx?k=&c=2&m=-1&ps=20
and found one nice validation pattern,
(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?
While i work in MVC view, it gives me error so i have change it to
(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@@?^=%&:/~\+#]*[\w\-\@@?^=%&/~\+#])?
i.e.
@@
instead of @
when it runs and if i see the console, i got the original one, so i think it is okay for me to do@@
instead of @
But in console i got an error
can anyone tell me what is wrong with this, so got the error,
"invalid range in character class"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

解决此问题的最简单方法:在 javascript 验证器中,删除
new RegExp()
以及引号,并在开头和结尾添加斜杠,表示正则表达式文字。因为您的正则表达式位于字符串中,所以“\”被解释为字符串转义,而不是正则表达式转义,本质上意味着所有“\”都将被删除。您可以通过不使用字符串而是使用 javascript 正则表达式文字来避免这种情况:如果使用 RegExp() 创建表达式,则必须在每个地方使用
\\
\
发生。正如评论中提到的,将两个
&
替换为&
(在您获取正则表达式的服务器上进行双重 HTML 编码)。它们在正则表达式语法中并没有错误,但它们确实使表达式允许使用;
,而这在 URL 中是不允许的。更新/解释
错误的实际含义是,由于 javascript 在创建最终正则表达式时忽略了字符串中的所有反斜杠,因此变成:
[\w\-_]< /code> 表示“匹配任何单词(字母数字)字符、连字符或下划线”。
[w-_]
表示“匹配“w”和“_”之间的任何字符。但是“w”实际上位于“_”之后(查看 ASCII/UTF -8 个字符表)意味着它是字符类中的一个无效范围(“字符类”=“要匹配的字符集合”)
Easiest way to fix this: In the javascript validator, remove
new RegExp()
as well as the quotes, and add slashes at beginning and end, indicating a regex literal. Because your Regex is in a string, "\" is interpreted as a string escape, rather than a regex escape, essentially meaning all the "\" will be removed. You avoid that by not using a string, but a javascript regex literal:If creating the expression using RegExp(), you'd have to use
\\
in every place\
occurs.As mentioned in the comment, replace two
&
with&
(double HTML encode on server you got the regex from). They're not wrong in Regex syntax, but they do make the expression allow for;
, which isn't allowed in a URL.Update/explanation
The actual meaning of the error is that because javascript ignores all the backslashes in the string when creating the final regex, it turns into:
[\w\-_]
means "match any word (alphanumeric) character, a hyphen or an underscore".[w-_]
means "match any character between "w" and "_".But "w" actually comes after "_" (look at an ASCII/UTF-8 character table) meaning it's an invalid range in the character class ("character class" = "collection of characters to match")