4 votes

Validate field only letters and spaces with Request Laravel

I am validating the input text and I have an input called 'name' where I want to enter only letters whether lowercase, uppercase, spaces, with or without tilde and the letter 'ñÑ', but no numbers. This is my code:

MyRequest

public function rules()
    {
        return [
            'departamento'=>'required|integer|not_in:0',
            'nombre'=>'required|regex:([a-zA-ZñÑáéíóúÁÉÍÓÚ\s]+)'
        ];
    }

Everything is fine but there is a problem and if I put for example "Name1", it tells me normal when it should tell me that the field is not valid, that's my problem. I need help please :s

3voto

Shaz Points 22941

EDITION:

To validate letters and spaces If you do not use a regex, you must use a regex or create a custom rule:

'nombre' => 'required|regex:/^[\pL\s\-]+$/u',

If you want to create the custom rule, you can check the Laravel documentation.


To validate ONLY letters, there is the alpha rule:

'nombre' => 'required|alpha',

More information in the Laravel documentation: https://laravel.com/docs/5.7/validation#rule-alpha


This is its source code:

/**
 * Validate that an attribute contains only alphabetic characters.
 *
 * @param  string  $attribute
 * @param  mixed   $value
 * @return bool
 */
public function validateAlpha($attribute, $value)
{
    return is_string($value) && preg_match('/^[\pL\pM]+$/u', $value);
}

0 votes

If I enter 2 texts I get an error with 'alpha'.

0 votes

So it's not just letters you want to validate, that's what the title says.

0 votes

Where I write my case I also ask for spacing :s

HolaDevs.com

HolaDevs is an online community of programmers and software lovers.
You can check other people responses or create a new question if you don't find a solution

Powered by:

X