Javascript value validation using PHP on Webserver.
Mirko Steiner - 2009/01/01
In mondern Webdesign people often want to validate form data on the client side before sending the data to the webserver. So that the whole page hasn't to be send to the server, got validated, and then (in the case, some value is wrong) send the same page again with highlighting the uncorrect values.
Javascript gives the posibility to do that, but you code the validators twice: first in PHP, second in Javascript. This results in maintaining the same functionality twice the time (this sucks!), also you have to ensure that the validators works excatly the same way (this sucks!), and last but not least: initially you have to code the same stuff twice! (still sucking!)
Then, i got an Idea! Why don't use the already finnished, allready working, crucial (*1) PHP code on the webserver that validates the data, with Javascript on the client side?
Due the use of setter methods you have the great ability to check the data before you set them to a private member, why not using this already working functionality on the client side?
On the Client you can send requests with the XMLHttpRequest() Javascript Class to the webserver, evaluating the result and partialy modfify the webpage - this technology if formely known as Ajax - but i don't like this term and also i missed some things to be 100% Ajax "conform".
So i coded an example class, named Foo with two private members: A and B. Due the members are private, it is not possible to set them from "outside", so there a two setter methods: setA() and setB(). Each of this methods uses a checker method to validate the value you want to set on correctness and these methods are public and static!
This means, you can use these methods, without creating an object. So you can check if your value is correct for using with setA(). With this isolated functionality I created a bit "glue code" to send a value from javascript to the server, check them with the related method (in PHP!) and give a result so that the javascript on the client side can act (in this case setting the input field green or red).
Here are the stuff:
- test.php - The Testpage (take a look into the source code!) *2
- Foo.php - The Foo Class
- check.php - The "glue code"
*2 The Javascript code doesnt work with all browsers (i tested successfully with Mozilla Firefox, Apple Safari and Google Chrome) - it should give you only an impression how to realize it.