简体   繁体   中英

javascript RegExp validate url expression

I have already found many posts on this subject, however no post handles my specific issue.

This is the regex that I use (found on this website) :

function validateUrl(value){
        return /[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}([-a-zA-Z0-9@:%_\+.~#?&//=]*)/i.test(value);
}

This validates my url correct till up to the following point:

mydomain.tld/mypage/this'go(es{wro[ng

My function returns true, even when there are not-allowed characters like:
' or " or ( or ) or [ or ] or { or }

I don't understand why this is allowed. I have this: [-a-zA-Z0-9@:%_\\+.~#?&//=]
Should return ' false ' in my opinion...

Your regex almost works. In the string mydomain.tld/mypage/this'go(es{wro[ng it matches mydomain.tld/mypage/this . As you didn't put anchors in both ends, it does match ( partially ).

Just change it to:

^[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}([-a-zA-Z0-9@:%_\+.~#?&\/\/=]*)$
^                                                                        ^

See LiveDemo

Please try this:

function validateUrl(value){
        return /^(http(s)?:\/\/)?(www\.)?[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$/.test(value);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM