Simple Server-side Ajax Form Validation
Contents
Download
Valerie requires PHP4 and MooTools 1.2b2. Choose your preference:
- Skinny (compressed core files)
- Average (compressed core files with MooTools 1.2b2)
- Chubby (uncompressed files with demo and documentation)
If you've got any problems, suggestions or translations, head on over and leave me a note.
Demo
Go ahead, try it out.
Usage
This code indicates a required step.
This code indicates steps used to enable non-javascript usability.
Place this at the top of your form page:
<?php session_start(); $_SESSION['referer'] = $_SERVER['PHP_SELF']; ?>
Include a couple scripts and initialize Valerie in the head:
<script type="text/javascript" src="path/to/mootools.js"></script> <script type="text/javascript" src="path/to/valerieclient.js"></script> <script type="text/javascript"> window.addEvent('load', function(){ new ValerieClient('form_id'); }); </script>Construct your form like this:
<form id="form_id" method="post" action="validation_page.php"> <input type="text" name="field_1:rule1|rule2(arg1,arg2)" id="field_1" value="<?php echo $_SESSION['valerie']['field_1']; ?>" /> <?php echo $_SESSION['valerie']['field_1_error']; ?> </form>
In the form action page place the following:
require_once('path/to/valerie.php'); $myValidator = new ValerieServer($_POST); $data = $myValidator->validate(); // process $data ... $myValidator->back();
Customizations
Localization
To change the language pack, simply pass in the filename upon instantiation of Valerie server-side.
$myValidator = new ValerieServer($_POST, 'en.php');
There is also one message client-side that must be passed in upon instantiation:
new ValerieClient('form_id', {'ERROR': 'Error message in your language.'});
If you really wanted to, you could just add that message to your language pack and include that in the form page so you could then do this:
new ValerieClient('form_id', {'ERROR': '<?php echo VAL_ERROR; ?>'});
To make your own language pack, just copy localization/en.php and translate it to your own language. Be sure to keep it in the localization directory.
Defining Events
You'll probably want to change the way certain events are handled, like how the error messages are displayed. To do that, just pass in an object with the events you want to overwrite. Events include onInitialize, onFormValidate, onFormInvalidate, onFieldValidate, onFieldInvalidate, onBeforeSubmit, onSubmitted, and onError.
new ValerieClient('form_id', {
'onFormValidate': function () {
alert("Your form has been successfully submitted.");
},
'onFormInvalidate': function (response) {
var count = response.content.length;
alert("Your form has " + count + " errors, but you have to guess what they are.");
}
}
You can look in the class at the default events to get an idea how to write your own. Every event is automatically passed the instance of Valerie. Additionally, onFormValidate, onFormInvalidate, onFieldValidate, and onFieldInvalidate receive the parsed JSON response from the server.
Defining Rules
It's pretty easy to define your own validation rules. You have the choice to use a regular expression or a function. Before you validate the data, just register your new rules.
$myValidator = new ValerieServer($_POST);
$myValidator->register(array(
'rule_name' => array('regex or function name', "Error message."),
'digit' => array('/^\d$/', "This field must contain a single numerical character."),
'less_than' => array('is_less_than', "{1} is not less than {2}");
));
$data = $myValidator->validate();
function is_less_than($val, $arg, $err) {
$err = ValerieServer::format($err, array($val, $arg));
return array((float) $val < (float) $arg, $err);
}
Let me explain the function is_less_than() a little bit. First, you'll notice that it automatically receives the field value, any arguments you may have passed in the html, and the error message. You have the option of returning the result plus the error message with substituted values. If you don't want to change the message, just return the boolean result. Here's how you'd use it in the html:
<input type="text" name="field_id:less_than(5)" id="field_id" />
Secondly, you'll notice I used a couple tokens in the error message that I replaced with Valerie::format(). I included a few helper methods that I'll explain next.
Need Help?
Lets take a look at some helper methods in action:
$iHeartValerie = new ValerieServer($_POST);
$ajax = $iHeartValerie->is_ajax();
$iHeartValerie->register(array(
'less_than_field' => array('is_less_than_field', "This field has to be less than the value in {1}.")
));
$data = $iHeartValerie->validate();
function is_less_than_field($val, $args, $err) {
global $iHeartValerie;
list($name, $label) = ValerieServer::get_name_label($args);
$val2 = $iHeartValerie->get_value($name);
if (ValerieServer::is_empty($val2)) {
return true;
} else {
$err = ValerieServer::format($err, $label);
return array((float) $val < (float) $val2, $err);
}
}
ValerieServer::back($ajax);
And this is how we'd use our new rule:
<label for="age">Your Age<label> <input type="text" name="age:int" id="age" /> <label for="ch_age">Your Child's Age<label> <input type="text" name="ch_age:less_than_field(age,Your_Age)" id="ch_age" />
Documentation
Class: ValerieServer
Function: Constructor
Creates a new instance of ValerieServer.
Syntax
new ValerieServer($data[, $lang])
Arguments
- $data - (array) Post data to be validated.
- $lang - (string, optional: defaults to 'en.php') Language pack to use.
Returns
- (object) A new ValerieServer instance.
Example
$myValidator = new ValerieServer($_POST);
Function: validate
Validates data stored in ValerieServer instance.
Syntax
ValerieServer->validate()
Returns
- (array) An array of validated POST data.
Example
$data = $myValidator->validate();
Function: register
Adds new rules to check fields against.
Syntax
ValerieServer->register($patterns)
Arguments
- $patterns - (array) Array of new rules.
Example
$myValidator->register(array(
'available' => array('is_available', "This username is not available. Please choose another.");
));
function is_available($val) {
// check the database to see is username is available
return $result;
}
Function: back
Redirects user back to form if the request is not ajax.
Syntax
ValerieServer->back([$ajax])
Arguments
- $ajax - (bool, optional) Indicates if the request is ajax.
Example
$myValidator->back(); // OR ValerieServer::back($is_ajax);
Function: get_name_label
Returns an array with the second element filtered (underscores are replace with spaces).
Syntaxt
ValerieServer::get_name_label($args)
Arguments
- $args - (mixed) A string or array containing a name and label.
Returns
- (array) An array with a length of 2 containing a name and label (if it exists).
Example
$name = 'field_1';
$nameLabel = array('field_1', 'Field_Label');
$field = ValerieServer::get_name_label($name);
// $field contains: array('field_1', 'field 1');
$field = ValerieServer::get_name_label($nameLabel);
// $field contains: array('field_1', 'Field Label');
Function: get_value
Gets the value of a field.
Syntax
ValerieServer->get_value($id);
Arguments
- $id - (string) Name of the field.
Returns
- (string) The value of the field.
Example
$myValidator->get_value('field_1');
Function: get_rule
Gets the rule of a field.
Syntax
ValerieServer->get_rule($id)
Arguments
- $id - (string) Name of the field.
Returns
- (array) The rule(s) that the field is validated against.
Example
$myValidator->get_rule('field_1');
Function: is_empty
Checks if a field is empty.
Syntax
ValerieServer::is_empty($val)
Arguments
- $val - (string) The value to test.
Returns
- (bool) Indicates if the value is empty.
Example
ValerieServer::is_empty($myValidator->get_value('field_1'));
Function: format
Replaces tokens ({1}, {2}, ... {n}) with the values passed in.
Syntax
ValerieServer::format($template, $values)
Arguments
- $template - (string) A string that contains tokens.
- $values - (mixed) A string or array with values.
Returns
- (string) A string with tokens replaced with values.
Example
$message = 'Hello, {1}. How are you {2}?';
$content = array('Henry', 'today');
$message = ValerieServer::format($message, $content);
// $message contains: 'Hello, Henry. How are you today?.'
Rules: ValerieServer
Rules that field values can be validated against.
Syntax
field_id:rule1|rule2(arg1,arg2)
required
Checks if field contains a value.
requiredif(id[, label])
Checks if field contains a value only if the passed in field contains a value.
Arguments
- id (string) - Id of the field to check first.
- label (string, optional: defaults to id) - Label to use in error message.
confirm(id[, label])
Checks if field contains same value as the field passed in.
Arguments
- id (string) - Id of the field to check first.
- label (string, optional: defaults to id) - Label to use in error message.
differ(id[, label])
Checks if field contains a value different from the field passed in.
Arguments
- id (string) - Id of the field to check first.
- label (string, optional: defaults to id) - Label to use in error message.
maxlength(length)
Checks if field contains a value not longer than length (inclusive).
Arguments
- length (int) - The maximum length of the field.
minlength(length)
Checks if field contains a value not shorter than length (inclusive).
Arguments
- length (int) - The minimum length of the field.
int
Checks if field contains an integer.
alpha
Checks if field contains only alphabetic characters.
alphanumeric
Checks if field contains only alphanumeric characters.
currency
Checks if field contains US currency.
date
Checks if field contains a date.
time
Checks if field contains a 12-hour time value.
time24
Checks if field contains a 24-hour time value.
phone
Checks if field contains a US telephone number.
phoneintl
Checks if field contains an international telephone.
postal
Checks if field contains a postal code.
zip
Checks if field contains a ZIP code.
email
Checks if field contains an email address.
url
Checks if field contains a URL.
ip
Checks if field contains an IP address.
Class: ValerieClient
Function: Constructor
Creates a new instance of ValerieClient.
Syntax
new ValerieClient(form[, options])
Arguments
- form - (mixed) Id or reference to the form to be validated.
- options (object, optional) Options and events to set.
Options
- validateOnKeyUp - (bool) Validate while the user types.
- ERROR - (string) The message to display when there's an error.
Events: ValerieClient
Events that can be attached to an instance of ValerieClient.
-
onInitialize
(function) Fires when the class is instantiated.
Arguments
- (object) Instance of ValerieClient.
-
onFormValidate
(function) Fires when the form is validated.
Arguments
- (string) The validation success message.
- (object) Instance of ValerieClient.
-
onFormInvalidate
(function) Fires when the form is invalidated.
Arguments
- (array) Array of objects with members 'id' and 'message'.
- (object) Instance of ValerieClient.
-
onBeforeSubmit
(function) Fires when user submits the form but before the form is sent.
Arguments
- (object) Instance of ValerieClient.
-
onSubmitted
(function) Fires when form validation results are returned.
Arguments
- (object) Instance of ValerieClient.
-
onError
(function) Fires when an error occurs with form submission.
Arguments
- (object) Instance of ValerieClient.
-
onFieldValidate
(function) Fires when a single field is validated (and validateOnKeyUp is true).
Arguments
- (string) Id of the validated field.
- (object) Instance of ValerieClient.
-
onFieldInvalidate
(function) Fires when a single field is invalidated (and validateOnKeyUp is true).
Arguments
- (object) Object with members 'id' and 'message'.
- (object) Instance of ValerieClient.