Hello all,
I would like to have your help in order to find the simplest way, to deal with this validation error messages.
I know that we could have an abstract validation class and then have the string validation class and numeric validation class etc… I know we can do thinks much better, but I just need to understand how do deal with the error messages on this case.
Here is what I have:
class Validacao
{
private $_msgErro=array();
public function limpaString($campoForm)
{
if (!empty($campoForm))
{
$campoForm = filter_var($campoForm, FILTER_SANITIZE_STRING);
}
}
public function validaNumero($campoForm)
{
if (!empty($campoForm))
{
if(filter_var($campoForm, FILTER_VALIDATE_INT) === false)
{
$this->_msgErro[$campoForm] .= ' Introduza um valor inteiro válido. ';
}
}
}
public function validaStringMinMax($campoForm, $min, $max)
{
if (!empty($campoForm))
{
//se o campo for menor que o mínimo ou maior que o máximo
if ((strlen($campoForm) < $min) || (strlen($campoForm) > $max))
{
//echo' Tenha em atenção a dimensão daquilo que quer introduzir.';
//$this->_msgErro[$campoForm] .= 'Insere entre: '.$min.' e '$max;
}
}
}
public function requerido($campoForm)
{
if ($campoForm=="")
{
if (isset($this->_msgErro[$campoForm]))
{
$this->_msgErro[$campoForm] .= ' Campo obrigatório. ';
}
else
{
$this->_msgErro[$campoForm] = ' Campo obrigatório. ';
}
}
}
public function validaEmail($campoForm)
{
if (!preg_match("^[a-zA-Z0-9_\\.\\-]+@[a-zA-Z0-9_\\.\\-]*[a-zA-Z0-9_\\-]+\\.[a-zA-Z]{2,4}$^", $campoForm))
{
$this->_msgErro[$campoForm] = 'O e-mail não é válido.';
}
}
public function errosValidacao()
{
return $this->_msgErro;
}
}
Usage:
If I want to validate and clean a string field that is required and other things, something like this is been used:
//limpeza e validacao:
$val = new Validacao();
$val->requerido($tituloNoticia);
$val->limpaString($tituloNoticia);
$val->validaStringMinMax($tituloNoticia, 3, 84);
Then I use the last method on this class to check if there are errors or not:
if (!$val->errosValidacao())
{
try
{
If they exist, on my form I would have something like this near the form field:
<?php echo (isset($val->errosValidacao('tituloNoticia'))) ? '<br /><span class="mensagem-erro-ss">'.$val->errosValidacao('tituloNoticia').'</span><br />':''; ?>
My issue is that I cannot find a way to display the error messages to the user.
I have tried to change errosValidacao() method on several ways already, by adding $campoForm as argument, or to return $this->_msgErro[‘campoForm’], but I’m getting no luck, always getting either undefined index or undefined variable notices.
Can I have a push?
Thanks in advance,
Márcio