Validating url with jQuery without the validate-plugin?

后端 未结 7 681
情书的邮戳
情书的邮戳 2020-11-28 23:06

I need to validate a url in variable with jQuery, but can\'t use validate-plugin. Is there a simple way to do this?

7条回答
  •  暖寄归人
    2020-11-28 23:54

    If you are sure that your audience is using HTML5, you can use type="url" to validate the text string. You could also dynamically create an input element, set the type and test whether the variable is valid URL or not.

    The following is based on a blog post from https://www.raymondcamden.com/2016/10/19/using-html-form-validation-in-pure-javascript

    var elm;
    function isValidURL(u){
      if(!elm){
        elm = document.createElement('input');
        elm.setAttribute('type', 'url');
      }
      elm.value = u;
      return elm.validity.valid;
    }
    
    console.log(isValidURL('http://www.google.com/'));
    console.log(isValidURL('//google.com'));
    console.log(isValidURL('google.com'));

提交回复
热议问题