A small js coding issue needs your help, thanks in advance

Discussion in 'JavaScript' started by owntype, Dec 13, 2009.

  1. #1
    
    			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
     
    owntype, Dec 13, 2009 IP
  2. camjohnson95

    camjohnson95 Active Member

    Messages:
    737
    Likes Received:
    17
    Best Answers:
    0
    Trophy Points:
    60
    #2
    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
     
    camjohnson95, Dec 14, 2009 IP
  3. mariush1007

    mariush1007 Member

    Messages:
    40
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    43
    #3
    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-\u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|\/|\?)*)?$/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
     
    mariush1007, Dec 14, 2009 IP
  4. owntype

    owntype Well-Known Member

    Messages:
    1,169
    Likes Received:
    20
    Best Answers:
    0
    Trophy Points:
    130
    #4
    Thank you guys! both solutions work smoothly!

    Much appreciated!!
     
    owntype, Dec 14, 2009 IP