Skip to content

Instantly share code, notes, and snippets.

@marcnewton
Last active January 8, 2020 12:12
Show Gist options
  • Save marcnewton/37e7d07a962bf7eb8f2eef38626e6812 to your computer and use it in GitHub Desktop.
Save marcnewton/37e7d07a962bf7eb8f2eef38626e6812 to your computer and use it in GitHub Desktop.
Laravel International String Validation

Laravel International String Validation

Validate a string containing any international alpha character.

InternationalString.php should be placed in App\Rules -> App\Rules\InternationalString.php

Usage Example

Example shows usage with validate method from the Request instance in a Controllers store method handling a POST request.

    public function store(Request $request)
    {
        $request->validate([
            'label' => ['required', new InternationalString()],
        ]);

        $request->validated();

        $model = new MyModel();

        $model->fill($request->all());

        $model->saveOrFail();

        return $model;

    }

You can extend the valiation with custom characters, here spaces are included:

 'name' => [new InternationalString('\s')]

Validation allowing dashes and numerics, settings second parameter to true allows numerical values:

 'title' => [new InternationalString('\-',true)]

Validate with custom string message:

 'name' => [new InternationalString('\s',false,'Please enter a valid full name')]

Validate with custom translation key:

 'name' => [new InternationalString('\s',false,'user.fullname')]
<?php
/**
* Author: Marc Newton <[email protected]>
* Link: https://gist.github.com/marcnewton/37e7d07a962bf7eb8f2eef38626e6812
*
* Laravel custom validation rule.
* Pattern match for checking strings only contain alphabetical characters from various launguage writing systems.
*
* Accepts additional custom appended regex syntax.
*
* Confirmed supported script types: Cyrillic
*/
namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;
class InternationalString implements Rule
{
private
$extra,
$numbers,
$message;
/**
* InternationalString constructor.
* @param string $extra Optional appended regex syntax.
* @param bool $numbers If true then allow numerical 0-9.
* @param string|null $message Optionally specify a custom error message or translation key string.
*/
public function __construct($extra = '', $numbers = false, $message = null)
{
$this->extra = $extra;
$this->numbers = $numbers;
$this->message = $message ?: 'The :attribute contains invalid characters.';
}
public function passes($attribute, $value)
{
preg_match('/[^' . ($this->numbers ? '\p{N}' : '') . '\p{L}' . $this->extra . ']/', $value, $invalid);
return empty($invalid);
}
public function message()
{
return trans($this->message);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment