Twitter Feed

Xataface Maillist

Sign up to receive the Xataface news letter with weekly updates and development tips.

 

How to add custom validation with Delegate Classes

If the standard validators (e.g., required, email, regex, etc..) don't quite cut it for your validation rules, Xataface allows you to define custom validation methods in the delegate class.
Why might you want to define a custom validation method in the delegate class?
  • perform Credit Card or SIN checksumming
  • validate against a remote web service
  • some fields require more knowledge to validate than can be described in a simple regular expression.

This how-to requires basic knowledge of Delegate classes.  For a brief introduction to delegate classes, see http://framework.weblite.ca/documentation/tutorial/getting_started/delegate_classes.


Adding custom validation methods is easy with Xataface.  You just have to define methods in your delegate class the conform to the following interface:

function <fieldname>__validate( $record, $value, $params){}

where <fieldname> is the name of the field that the method should validate.  The parameters are as follows:

  • $record : A Dataface_Record object that is to be validated.
  • $value : The value that is to be stored in the field.
  • $params : An array that can be used to pass information out of the method. The 'message' key in this array can be used to pass back a failure message to be displayed in the browser if validation failed.
This method will return true if validation succeeds and false if it does not.

Examples

<?
// tables/Profile/Profile.php
// Delegate class for the Profiles table
class tables_Profiles {

/**
* Validation method for the CreditCard field.
* This is just an example. Suppose that there is another
* method defined elsewhere that knows how to validate
* credit card numbers to make sure that they are valid numbers.
*/
function CreditCard__validate( &$record, $value, $params=array()){
$result = validateCreditCardNumber($value);
if ( !$result ){
$params['message'] = "Sorry, this is an invalid credit card number.";
return false;
} else {
// Credit card number checks out OK.
return true;
}
}
}
?>

Notes:

  • You would not want to use this above method for credit card authorization (actually charging money to a credit card) because this validation method is called every time the record is saved.
  • The $record object is a Dataface_Record object.  It contains the state of the record prior to being updated.

See Also


Powered by Xataface
(c) 2005-2017 All rights reserved