Javascript – Regex for url validation (unterminated parentheticals error)

javascriptregexvalidation

I have the following expression to validate a URL but it gives me a syntax error on the browser. I am no expert in regex expressions so I am not sure what I am looking for. I would also like it to test for http:// and https:// urls.

"url":{
    "regex":"/^http\://[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(/\S*)?$/",
    "alertText":"URL must start with http://"}

Edit:

To clarify I am looking for help for both the regex and the syntax issues please. I have tried about 20 different variations based on all the answers but still no luck. Just to clarity, I do not need to validate the entire URL. I just need to validate that it starts with http:// or https:// but it must not fail validation if left empty. I can get the http part working with this

/^https?:///

no need to escape the / even. But it fails if the input field is empty, when I try:

/^(https?://)?/ 

I get an error saying "unterminated parenthetical /^(https?://)/".

Just to confuse matters more, here is one that I added yesterday to validate a date or no entry and it like the same sort of format to me.

/^([0-9]{1,2}\-\[0-9]{1,2}\-\[0-9]{4})?$/

Best Answer

For what it's worth, the syntax error is the unescaped forward slash here: /\S*

Edit: oh wow, I'm tired. All of the forward slashes are unescaped. You can escape them with a backslash: \/