if(url.match(/^(http(s?):\/\/|ftp:\/\/{1})?((\w+\.){1,})\w{2,}/) == null) { $('.error').hide(); $('#url_form').prepend('<div class="error">Enter a valid domain name!</div>'); } PHP: Hi, guys Need your kind help. I need to input a domain name then click submit to run the script. But in this js codes, if the domain name contains - (hyhpen) e.g. domain-name.com, then it returns error 'Enter a valid domain name!' How to modify it to let it works with hyphen domain? Thanks in advance
try a different Regex, here is one: [/code] /https?:\/\/([-\w\.]+)+\d+)?(\/([\w/_\.]*(\?\S+)?)?)?/ [/code] So change: if(url.match(/^(http(s?):\/\/|ftp:\/\/{1})?((\w+\.){1,})\w{2,}/) == null) to: if(url.match(/https?:\/\/([-\w\.]+)+\d+)?(\/([\w/_\.]*(\?\S+)?)?)?/) == null) i'm not sure how well this one works.... you'll have to test for yourself/ source: http://www.go4expert.com/forums/showthread.php?t=2262 another option: http://snippets.dzone.com/posts/show/452
to accept hyphen You need to change Your code only a little bit (in the middle of Your if statement change 'w' into '[a-zA-Z0-9_-]' as below): if(url.match(/^(http(s?):\/\/|ftp:\/\/{1})?((\[a-zA-Z0-9_-]+\.){1,})\w{2,}/) == null) { $('.error').hide(); $('#url_form').prepend('<div class="error">Enter a valid domain name!</div>'); } Code (markup): anyway above way is far to be perfect solution (for url validating purpose), instead try another code with different regular expression as below: var re = /^(https?|ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i; if(url.match(re) == null) { $('.error').hide(); $('#url_form').prepend('<div class="error">Enter a valid domain name!</div>'); } Code (markup): above regular expression is from jquery.validate.js plugin and for sure it is more appropriate way to test urls