Skip to content

Instantly share code, notes, and snippets.

@morales2k
Last active May 5, 2018 22:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save morales2k/a311ddc73c313caa2567701ea92b5e90 to your computer and use it in GitHub Desktop.
Save morales2k/a311ddc73c313caa2567701ea92b5e90 to your computer and use it in GitHub Desktop.
Some custom Laravel validation rules
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Validator;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
// Thanks to Nady Shalaby for this answer: https://stackoverflow.com/a/39331613
// Profile: https://stackoverflow.com/users/6521046/nady-shalaby
Validator::extend('phone', function($attribute, $value, $parameters, $validator) {
// regex tests: https://regex101.com/r/qq2QyF/1
return preg_match('/^([0-9]{3})-([0-9]{3})-([0-9]{4})$/i', $value);
});
// Validate alpha-dash plus spaces. Good for when the full-name is in just one field and we need users typing their names and lastnames in one field
Validator::extend('alpha_dash_space', function($attribute, $value, $parameters, $validator) {
// https://regex101.com/r/KTz4vs/1
return preg_match('/^[a-z0-9-_\s\.]+$/i', $value);
});
}
/**
* Register any application services.
*
* @return void
*/
public function register()
{
//
}
}
@morales2k
Copy link
Author

morales2k commented Sep 15, 2017

https://regex101.com/r/kActm6/2

The regex has some tests on here with regular US phone numbers, one finnish phone number and one argentinean phone number, all producing positive match results.

Need to make sure we don't produce positive matches when syntax is wrong... but for the most part, this regex will work for international phone numbers.

Feel free to suggest changes if you're feeling helpful.

@morales2k
Copy link
Author

Updated to add a forgotten i flag for the regex matching to be case insensitive.

@morales2k
Copy link
Author

Updated to add an alpha-dash-space validator.

@morales2k
Copy link
Author

morales2k commented May 5, 2018

Updated to remove overly complicated regex that attempted to match international numbers. Seems to be a better solution to simply match for what one needs in any specific application use-case. This latest version is the definitive regular use case for me. Also removed the replacer methods on the validation as they override whatever we use inside the request class' messages method.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment