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"
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:
ReplyDeletevar urlregex = /(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?/;
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:
/(http|ftp|https)://[w-_]+(.[w-_]+)+([w-.,@?^=%&:/~+#]*[w-@?^=%&/~+#])?/
The original [\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")