From past posts you could probably ascertain that I’ve taken quite a liking to jQuery. Lately I’ve been developing a form for my brother, Karl’s drafting service and have used this handy javascript framework. There is a jQuery plugin that I’ve been working with called Really Simple Validation that presents a simple, easy-to-use way of validating your forms before submitting them. It also allows an individual to implement their custom functions for validating your forms.
Karl’s order form required a specific phone number format (xxx-xxx-xxxx). Unfortunately, Really Simple Validation does not have pre-made phone number validation. I scoured the internet for such a function to no avail, so I decided to write my own custom function for RSV. It’s fairly simple and straightforward. Here is the javascript code:
function phoneValid()
{
var phoneRE = /^\d\d\d\-\d\d\d-\d\d\d\d$/;
var val = document.getElementById(“phone”).value;
if (!val.match(phoneRE)) {
var field = document.getElementById(“phone”);
return [[field, “Please enter a valid phone number format (xxx-xxx-xxxx).”]];
}
return true;
}
The first variable created (phoneRE) is a regular expression and is used to match the sequence of phone number (xxx-xxx-xxxx). The second variable (val) is the value of the particular form input field that has the id of “phone”. Below that is a conditional statement that returns an error message if the value of the input field doesn’t match the particular regular expression defined as phoneRE. If you look within that statement you’ll see “return [[field, “Please enter a valid phone number format (xxx-xxx-xxxx ).”]];”. This area is required for RSV and will display the message if an error is thrown. The field variable points to the form input field with the id “phone”.
Now that the function is created you just need RSV to make a call.
$(“#order_form”).RSV({
onCompleteHandler: myOnComplete,
rules: [
“function,phoneValid”,
]
});
To make this coexist within your form you will have to change “#order_form” to the particular id that you have given to your form. If you look at the line: “function, phoneValid”, you’ll see where the function we created above is being be called.
That’s it! For those new to jQuery remember that you need to include the jQuery script and the RSV plugin script as described in the links above.