Sunday, February 13, 2011

Dynamic validation of input with prototype

Context: You're stuck with prototype and you have a client that wants to validate some input with javascript. My case was "if a value exists then validate that it doesn't change by more than 20% - we want it highlighted it when you tab out". Aparently server side validation wasn't wanted, just a visual prompt.

Anyway - since my googlefu isn't up to scratch for mooching good javascript solutions that other people did I coded it myself (shocking!). Hopefully this helps someone. If not go switch to jQuery - seriously...

Back on topic again, wn load this creates a handler for each input that you find with your selector. The handler is a closure that uses the input's current value for relative validation, ie if the value was 1.0 when the form loaded then it would add the 'warning' class to the input if it was more than 1.2 or less than 0.8 after it's changed.

If you want more heavy handed validation (and you likely will) you can do harsher things like refusing to submit the form (good) or redirecting them to failblog (even gooder).

*What the hell is with Event.element(event) - if anyone knows a nicer way of doing this please let me know...