Skip to content

Instantly share code, notes, and snippets.

@niraj-shah
Last active February 19, 2016 12:26
Show Gist options
  • Save niraj-shah/9dfdb34de7fc7a083b73 to your computer and use it in GitHub Desktop.
Save niraj-shah/9dfdb34de7fc7a083b73 to your computer and use it in GitHub Desktop.
Laravel 5.x Custom Validation Rule: startswith
// 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