problema con la maquinilla de afeitar MVC de validación de URL y JQuery

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.

Tengo una referencia de 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\-\@@?^=%&/~\+#])?

es decir,

@@ en lugar de @

when it runs and if i see the console, i got the original one, so i think it is okay for me to do @@ en lugar de @

But in console i got an error

enter image description here

can anyone tell me what is wrong with this, so got the error,

"invalid range in character class"

preguntado el 31 de enero de 12 a las 08:01

Not an answer as such, but those two "&" aren't actually supposed to be "&", but just "&" - they've been HTML-encoded once too often by the website you got the regex from. -

1 Respuestas

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:

var urlregex = /(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?/;

If creating the expression using RegExp(), you'd have to use \\ in every place \ ocurre.

As mentioned in the comment, replace two & con & (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-@?^=%&/~+#])?/
  • El 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 después de "_" (look at an ASCII/UTF-8 character table) meaning it's an invalid range en el objeto clase de personaje ("character class" = "collection of characters to match")

Respondido el 31 de enero de 12 a las 14:01

Answer with great explanation, Thanks very much - amit patel

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.