Last active
May 5, 2018 22:52
-
-
Save morales2k/a311ddc73c313caa2567701ea92b5e90 to your computer and use it in GitHub Desktop.
Some custom Laravel validation rules
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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() | |
{ | |
// | |
} | |
} |
Updated to add a forgotten i
flag for the regex matching to be case insensitive.
Updated to add an alpha-dash-space validator.
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
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.