I've made this validation class in PHP that would take inputs, on initialization sanitize them and validate them specific to the type. It works fine, but I would like to know if there's some bad practice involved and how I can improve it. I would also love to hear if there's anything that makes the code awful or hard to read. Does it follow good coding standards? If not, how can I improve it?
Class Validate {
//Take the user input into the data put it to a class.
private $data; //Function argument
private $err; // boolean
public $empty;
private $errMsg;
public function __construct($data) { //Not sure about this one. Have to check it out later and decide
//perform some basic level validation like checking for emptiness.
foreach ($data as $k =>$v) {
$data[$k]= $v;
if($this->checkEmpty($v)==1) {
$this->empty=true;
}
}
}
private function checkEmpty($data) {
if($data==""|| empty($data) || !isset($data)) {
return 1;
}
}
private function basicSanitize($data) { //Basic level input santization to be used by other functions only.
$data=htmlspecialchars($data);
$data=trim($data);
$data=stripslashes($data);
return $data;
}
public function sanitize($data) { // Sanitization at a massive level to sanitize a lot of inputs at one go.
foreach ($data as $k =>$v) {
$this->data[$k]= $this->basicSanitize($v);
}
return $this->data;
}
public function name($data) {
if(strlen($data)<3) {
$this->errMsg = "Name too short.";
}
else if(strlen($data)>100) {
$this->errMsg = "Name too big.";
}
if(isset($this->errMsg)) {
return $this->errMsg;
}
else return true;
}
public function email($data) {
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$this->errMsg = "Invalid email format";
}
if(isset($this->errMsg)) {
return $this->errMsg;
}
else return true;
}
}
And here is calling the class:
$name="J";
$email="mephone@2d.com";
$input= array (
'name'=>$name,
'email'=>$email
);
$val=new Validate($input);
if($val->empty==false) {
$clean=$val->sanitize($input);
$nameErr = $val->name($clean['name']);
if($nameErr) {
echo $nameErr;
}
else echo $clean['name'];
Should I be calling the error messages like that? What could be a more systematic and better way to do that?