Skip to content

Instantly share code, notes, and snippets.

@niraj-shah niraj-shah/startswith.php
Last active Feb 19, 2016

Embed
What would you like to do?
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
You can’t perform that action at this time.