Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

laravel validation rule for only letters

Tags:

regex

php

laravel

I am trying to add a validation rule to only accept letters. I am using the regex rule but its still not working. Here is my code below:

    /**
     * Validate request/input 
     **/
    $this->validate($request, [
        'name' => 'required|regex:/^[\pL\s\-]+$/u|max:255|unique:users,name,'.$user->id,
        'email' => 'required|email|max:255|unique:users,email,'.$user->id,
    ]);

Whenever I enter a name like Foo Foo, it is still succesful in signing up.

Any idea what I am doing wrongly?

like image 359
hello world Avatar asked Jul 26 '16 19:07

hello world


People also ask

What is Validation rule in Laravel?

This validation rule runs validation checks against a field only if that field is present in the input array. #15) URL – url Under this validation rule, the field must be a valid URL. In this example, we are going to create a student registration form with basic Laravel validation.

How to validate alphabetic characters in Laravel?

Laravel doesn't have a built in validator for alphabetic characters and spaces, but it does give us everything we need to build one. It matches unicode characters, so poor João Gabriel won't have his name marked as invalid anymore :) Define your custom validation message in lang/xx/validation.php:

What is the current_password rule in Laravel 9?

The field under validation must be numeric. The field under validation must match the authenticated user's password. This rule was renamed to current_password with the intention of removing it in Laravel 9. Please use the Current Password rule instead.

What is a reset button in Laravel?

Description: A reset button allows the user to set form fields to its original values. Example: Generating a reset button. The following list shows some Laravel validation rules: Note: Refer to the official documentation of Laravel validation to see the full list of validation. Some of the important rules are listed below.


2 Answers

According to laravel documentation you can use :

  • alpha for entirely alphabetic characters
  • alpha_dash for alpha-numeric characters, as well as dashes and underscores and finally
  • alpha_num for entirely alpha-numeric characters.
like image 150
Amir Hassan Azimi Avatar answered Sep 23 '22 12:09

Amir Hassan Azimi


Your regex fails I think, I tried it on Regexr and couldn't get it to function, try this:

'name' => 'required|regex:/^[a-zA-Z]+$/u|max:255|unique:users,name,'.$user->id,

Let me know how you get on.

Here's the regex only: ^[a-zA-Z]+$

like image 29
ExohJosh Avatar answered Sep 22 '22 12:09

ExohJosh