How to validate persian slug in laravel?

Member

by addison , in category: PHP Frameworks , 3 months ago

How to validate persian slug in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by jerad , 3 months ago

@addison 

To validate a Persian slug in Laravel, you can create a custom validation rule using the following steps:

  1. Create a new validation rule by running the following command in your terminal:
1
php artisan make:rule PersianSlug


This will generate a new file in the app/Rules directory called PersianSlug.php.

  1. Open the app/Rules/PersianSlug.php file and add the following code to the passes method:
1
2
3
4
public function passes($attribute, $value)
{
    return preg_match('/^[p{L}p{N}]+(?:[-][p{L}p{N}]+)*$/', $value);
}


This code uses a regular expression pattern to match Persian slugs. The pattern allows for Persian letters and numbers, as well as hyphens in between words.

  1. Add a custom error message to the message method in the PersianSlug.php file:
1
2
3
4
public function message()
{
    return 'The :attribute field must be a valid Persian slug.';
}


  1. Now, you can use the custom validation rule in your Laravel application by adding the following code to your validation rules:
1
2
3
4
5
use AppRulesPersianSlug;

$validatedData = $request->validate([
    'slug' => ['required', 'string', new PersianSlug],
]);


With these steps, you should now have a custom validation rule for validating Persian slugs in Laravel.