Set condition for checking url using jQuery validation


Sorry if the title of this thread doesn't make sense - I didn't know what to write :)

I am using jQuery form validation and one of the rules is to check for a valid url. The field isn't required so am just validating formatting. This all works fine but where the complication comes (for me anyway) is that I also have some javascript populating the field with http:// onfocus and removing onblur and I need to stop the url validation if the field is left blank but what is happening at the moment is that as soon as the focus is lost the form still looks for a valid url as the field has been focused on (hope some of this makes sense.

The code (I have removed all other rules for clarity)

// Pre-fill Online Profile URL form field with http:// on focus and remove on blur
	var text = "http://";
	$("#online_profile_url").focus(function() {
		if($(this).attr("value") == "") $(this).attr("value", text);
	$("#online_profile_url").blur(function() {
		if($(this).attr("value") == text) $(this).attr("value", "");
		rules: {
			online_profile_url: "url"

How can I only run the url validation if more than just the http:// has been input in the field (I don't know if and how to set conditionals within the rules)?


Apparently you can use 'depends'. See here on SO.


Thanks, I will have a play with that


Thank you so much @pritaeas I have implemented the function and it appears to be working brilliantly.

online_profile_url: { 
				url: {
					depends: function () {
						return $("#online_profile_url").attr("value") !== 'http://';
Thanks for sharing.
Question Answered as of 3 Years Ago by pritaeas
Isn't it about time forums rewarded their contributors?

Earn rewards points for helping others. Gain kudos. Cash out. Get better answers yourself.

It's as simple as contributing editorial or replying to discussions labeled or OP Kudos

This question has already been solved: Start a new discussion instead
Start New Discussion
Tags Related to this Article