Validation of regex URL

Asked

Viewed 301 times

-1

Good afternoon. I need to do a URL validation using javascript. I have the following regex:

/^(?:http(s)?:\/\/)?[\w.-]+(?:\.[\w\.-]+)+[\w\-\._~:/?#[\]@@!\$&'\ 
(\)\*\+,;=.]+$/gm

It turns out that if I type for example: www.test it validates. What I needed was for it to be validated too . com, . br, or any other extension with at least 2 characters. How can I add this to my regex?

  • 1

    Here has several options, and see that it is a regex more complicated than another, since validating URL with regex it’s not that simple. Anyway, I would take the second point out of the excerpt (?:\.[\w\.-]+)+ (just staying (?:\.[\w\-]+)+, or (?:\.\w+)+, otherwise the regex will accept several points in a row, see (I didn’t see if there were more things to fix)

  • Just out of curiosity, what if the person has an ending domain .io, or a domain with an end .eu?

  • 1

    The point is that www.teste is a valid URL in accordance with RFC 3986, as well as teste, /home, john@due, etc. If you do not wish to validate these values, I advise you to edit the question and describe exactly what the valid values would be.

  • Possible duplicate of Regular expression to validate urls

2 answers

0

Try using that expression:

^(?:https?:\/\/)?(w{3}\.)?[\w_-]+((\.\w{2,}){1,2})(\/([\w\._-]+\/?)*(\?[\w_-]+=[^\?\/&]*(\&[\w_-]+=[^\?\/&]*)*)?)?$

You can test on the link: https://regex101.com/r/0xIv1P/2

0

^(?:http(s)?:\/\/)?[\w.-]+(?:\.[\w\.-]+)+[\w\-\._~:?#[\]@@!\$&'\ 
(\)\*\+,;=.]+$

Just take a bar :D. Test the one I sent up.

I always use the regex101.com site to test. Get in there so you can see how it works, it shows you what each part of your regex is doing by color, it’s very intuitive.

  • 1

    That regex considers that www.teste is valid, so I guess you haven’t fixed the problem: https://regex101.com/r/0xIv1P/1/

  • but if the person type google.com, must be valid right? or must be required www? @hkotsubo

  • I think that google.com is valid, but the question says that www.teste is not. Anyway, the regex that is in the question already validates google.com - https://regex101.com/r/3KmlUd/1/

  • 1

    That regex is pierced, validated www.as!.com.! ziriguidum.www.........1234@@@@@@@!!!####*())(+=-_;[]?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.