by aherrick
9. July 2008 05:12
Today I was working on some code and I needed to validate a textbox input when the user attempted to leave the field. The javascript event onblur fit the bill nicely.
In the code behind I wired up my textbox like so:
this.txtAmount.attributes.add("onblur", "validate()");
This will hook the onblur event onto the textbox programatically. I find it appropriate to add events progrmatically since Visual Studio complains about adding events to the markup. While this will still compile and run just fine, there is much more flexiblity in adding events in the code behind.
Now for the javascript code. First I am setting a reference to my textbox and a hidden field on the form. The first check is a regular express to make sure my input is valid. I am looking for positive amount.
For example: 2 valid, 200 valid, 200.20 valid, 200.233 invalid, -200 invalid.
If input does not pass the regex, I throw an alert asking for valid input. If it passes regex, my second check is just some business logic.
That is all it takes to write a custom javascript validation for your code. Thank you!