Lord Rixuel Lord Rixuel - 1 month ago 14
HTTP Question

How to use jQuery validation for the input type url without the protocol?

In my input field validation, I set the input type as "url".

URL that have the protocol "http://" or "https://" is valid.
Without it, the url is invalid.

Valid: http://www.foo.com

Valid: https://www.foo.com

Invalid: www.foo.com

Invalid: foo.com

In my code, everytime an URL link has no "http://" or "https://", a function, "checkURL()", is going to add it like the following code below.



// just for the demos, avoids form submit
jQuery.validator.setDefaults({
debug: true,
success: "valid"
});
$( "#myform" ).validate({
rules: {
field: {
required: true,
url: true
}
}
});

function checkURL(url) {
var string = url.value;

if (!~string.indexOf("http")) {
string = "http://" + string;
}

url.value = string;
return url;
}

<form id="myform">
<label for="field">Required, URL: </label><br>
<input type="url" id="field" name="field" onblur="checkURL(this)">
</form>

<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="http://cdn.jsdelivr.net/jquery.validation/1.15.0/jquery.validate.min.js"></script>
<script src="http://cdn.jsdelivr.net/jquery.validation/1.15.0/additional-methods.min.js"></script>





On the snippet, I enter "www.yahoo.com".

The moment I click outside of the field, the function checkURL adds "http://" to my input, so I get "http://www.yahoo.com".

The problem is after it adds "http://", jQuery validation still thinks the URL is invalid.

I have to click on the input field and then click outside of it again to make it knows it's valid.

Is there a way to make the validation valid after we enter an url without the protocol (ie: www.yahoo.com)?

EDIT: I forgot to put in my code
type="url"
for the input field.


It shouldn't be change to type="text"

Answer

Try using onchange instead of onblur

// just for the demos, avoids form submit
jQuery.validator.setDefaults({
  debug: true,
  success: "valid"
});
$( "#myform" ).validate({
  rules: {
    field: {
      required: true,
      url: true
    }
  }
});

function checkURL(url) {
    var string = url.value;
    
    if (!~string.indexOf("http")) {
        string = "http://" + string;
    }
    
    url.value = string;
    return url;
}
<form id="myform">
	<label for="field">Required, URL: </label><br>
	<input type="url" id="field" name="field" onchange="checkURL(this)">
</form>

<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="http://cdn.jsdelivr.net/jquery.validation/1.15.0/jquery.validate.min.js"></script>
<script src="http://cdn.jsdelivr.net/jquery.validation/1.15.0/additional-methods.min.js"></script>

What is the difference between onBlur and onChange attribute in HTML?