I am trying to validate a field in laravel controller; the logic is as follows, it is not mandatory to put information in the field, but if you enter information, I want to validate the content of that information to avoid XSS attacks.
//Obtener los datos
$obtenerDatos = array('titulo_banner' => $request->input('titulo_banner'));
//Validar los datos
$validarDatos = \Validator::make($obtenerDatos, [
'titulo_banner' => 'regex:/^[0-9a-zA-Z-ñÑáéíóúÁÉÍÓÚ ]+$/i'
]);
This is how I want to validate the information in that field, and it works for me if I get information in it, but if I want to leave it empty, it fails.
You can use nullable validation rule
With this, if the field arrives with a value
null
, the validation will pass, and if the value of the field is different fromnull
, the other rules that you add will be applied.So, for your case, the code can look like this: