public function validate($PostedFields, $Insert = false)
{
// Create an array to hold validation result messages
if (!is_array($this->_ValidationResults) || $this->resetOnValidate()) {
$this->_ValidationResults = array();
}
// Check for a honeypot (anti-spam input)
$HoneypotName = c('Garden.Forms.HoneypotName', '');
$HoneypotContents = getPostValue($HoneypotName, '');
if ($HoneypotContents != '') {
$this->addValidationResult($HoneypotName, "You've filled our honeypot! We use honeypots to help prevent spam. If you're not a spammer or a bot, you should contact the application administrator for help.");
}
$FieldRules = $this->defineValidationRules($PostedFields, $Insert);
$Fields = $this->defineValidationFields($PostedFields, $Insert);
// Loop through the fields that should be validated
foreach ($Fields as $FieldName => $FieldValue) {
// If this field has rules to be enforced...
if (array_key_exists($FieldName, $FieldRules) && is_array($FieldRules[$FieldName])) {
// Enforce them.
$Rules = $FieldRules[$FieldName];
// Get the field info for the field.
$FieldInfo = array('Name' => $FieldName);
if (is_array($this->_Schema) && array_key_exists($FieldName, $this->_Schema)) {
$FieldInfo = array_merge($FieldInfo, (array) $this->_Schema[$FieldName]);
}
$FieldInfo = (object) $FieldInfo;
foreach ($Rules as $RuleName) {
if (array_key_exists($RuleName, $this->_Rules)) {
$Rule = $this->_Rules[$RuleName];
// echo '<div>FieldName: '.$FieldName.'; Rule: '.$Rule.'</div>';
if (substr($Rule, 0, 9) == 'function:') {
$Function = substr($Rule, 9);
if (!function_exists($Function)) {
trigger_error(errorMessage('Specified validation function could not be found.', 'Validation', 'Validate', $Function), E_USER_ERROR);
}
$ValidationResult = $Function($FieldValue, $FieldInfo, $PostedFields);
if ($ValidationResult !== true) {
// If $ValidationResult is not FALSE, assume it is an error message
$ErrorCode = $ValidationResult === false ? $Function : $ValidationResult;
// If there is a custom error, use it above all else
$ErrorCode = val($FieldName . '.' . $RuleName, $this->_CustomErrors, $ErrorCode);
// Add the result
$this->addValidationResult($FieldName, $ErrorCode);
// Only add one error per field
}
} elseif (substr($Rule, 0, 6) == 'regex:') {
$Regex = substr($Rule, 6);
if (ValidateRegex($FieldValue, $Regex) !== true) {
$ErrorCode = 'Regex';
// If there is a custom error, use it above all else
$ErrorCode = val($FieldName . '.' . $RuleName, $this->_CustomErrors, $ErrorCode);
// Add the result
$this->addValidationResult($FieldName, $ErrorCode);
}
}
}
}
}
}
$this->_ValidationFields = $Fields;
return count($this->_ValidationResults) === 0;
}