Search code examples
asp.nettextboxjquery-validatepreset

Selective JQuery validation


I'm using JQuery Validation to validate a particular textbox in my form. The textbox is an optional website section, which uses the url validation method. This works fine and validates accordingly. I would like to have http:// preset into the textbox, to save the user having to type it. However, when the text is set, the validator becomes 'active', and prevents anything on the form being submitted until either the http:// is manually removed, or a valid website is entered. Is there a way of preseting text into the textbox, which won't cause the validator to start validating?

I tried to use

$("[id$='tbWebsite']").val("http://");

just before I call form.validate(), but it doesn't work (i.e. it still gets checked).

I've never used JQuery Validator before, so hopefully there's a fix for this that I'm missing!

An alternate solution for my case in particular, could be to activate the validator if a certain button is pressed (instead of any button on the form). Would that be possible?

Thanks

Update

I've added this to the textbox declaration:

onfocus="if(this.value == 'http://' || this.value == '')this.value='http://'" onblur="if(this.value == 'http://')this.value=''" 

That solves the main problem. However, if the user clicks in the textbox, then clicks away, the error message is still displayed (even though it's not enforced, and the form can be submitted). What would be the best way to ensure that the error message isn't displayed at all, if the value is 'http://'?


Solution

  • Put the prefix in only when the user focuses the empty textbox, and remove it if the textbox loses focus with only the prefix in it