Last active
February 19, 2016 12:26
-
-
Save niraj-shah/9dfdb34de7fc7a083b73 to your computer and use it in GitHub Desktop.
Laravel 5.x Custom Validation Rule: startswith
This file contains 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
// validate that mobile number starts with '07' | |
$rules = [ | |
'mobile' => 'required|numeric|startswith:07', | |
]; | |
// custom validator called startswith | |
Validator::extend('startswith', function( $attribute, $value, $parameters ) { | |
return substr( $value, 0, strlen( $parameters[0] ) ) == $parameters[0]; | |
}); | |
// custom replacer, so we can replace :value in the message | |
Validator::replacer('startswith', function( $message, $attribute, $rule, $parameters ) { | |
return str_replace( [':value'], $parameters, $message ); | |
}); | |
// Error message for startswith failure | |
$messages = [ 'startswith' => ':attribute needs to starts with :value' ]; | |
// validate input | |
$validation = Validator::make( Input::all(), $rules, $messages ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment