We're a community of 1077K IT Pros here for help, advice, solutions, professional growth and fun. Join us!
1,076,124 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Start New Discussion Reply to this Discussion

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", "");
	});
$("#appForm").validate({
		
		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)?

2
Contributors
3
Replies
36 Minutes
Discussion Span
1 Year Ago
Last Updated
4
Views
Question
Answered
simplypixie
Practically a Master Poster
642 posts since Oct 2010
Reputation Points: 157
Solved Threads: 118
Skill Endorsements: 5

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

pritaeas
Posting Prodigy
Moderator
9,286 posts since Jul 2006
Reputation Points: 1,173
Solved Threads: 1,457
Skill Endorsements: 86

Thanks, I will have a play with that

simplypixie
Practically a Master Poster
642 posts since Oct 2010
Reputation Points: 157
Solved Threads: 118
Skill Endorsements: 5

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://';
					}
				}
			}
simplypixie
Practically a Master Poster
642 posts since Oct 2010
Reputation Points: 157
Solved Threads: 118
Skill Endorsements: 5
Question Answered as of 1 Year Ago by pritaeas

This question has already been solved: Start a new discussion instead

Post: Markdown Syntax: Formatting Help
 
You
 
© 2013 DaniWeb® LLC
Page rendered in 0.0684 seconds using 2.65MB