Jump to content

Form validation class


AdRock

Recommended Posts

I have a validation class that i can use for more than one field on my form becuase the regex is the same. 

 

All i want to do is to change the field name of the output error message

 

So i call the class with the form input and the field name so when the error message is displayed, it says which field has the error

 

I call the class like this

$validators[]=new ValidateName($_POST['first_name'],'first_name');

The field validation class

<?php
    require_once 'includes/php/validators/Validator.php';

    class ValidateName extends Validator {
function validate($name, $field)
{
    if(empty($name)) {
	$this->setError('$field field empty');
    }
    else {
	if (!preg_match('/^[a-zA-Z -]+$/', $name)) {
	    $this->setError($field.' contains invalid characters');
	}
	if (strlen($name) < 2) {
	    $this->setError($field.' is too short');
	}
	if (strlen($name) > 30) {
	    $this->setError($field.' is too long');
	}
    }
}
    }
?>

 

and the validation class which sets the error message

<?php
class Validator {
var $errors;

function Validator($validateThis)
{
	$this->errors = array();
	$this->validate($validateThis);
}

function validate($validateThis) {}

function setError($msg)
{
	$this->errors[] = $msg;
}

function isValid()
{
	if (count($this->errors) > 0) {
		return FALSE;
	} else {
		return TRUE;
	}
}

function fetch()
{
	$error = each($this->errors);
	if ($error) {
		return $error['value'];
	} else {
		reset($this->errors);
		return FALSE;
	}
}
}
?>

Link to comment
https://forums.phpfreaks.com/topic/97613-form-validation-class/
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.