How to validate phone number in laravel 5.2? [closed] - php

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I want to validate user input phone number where number should be exactly 11 and started with 01 and value field should be number only. How do I do it using Laravel validation?
Here is my controller:
public function saveUser(Request $request){
$this->validate($request,[
'name' => 'required|max:120',
'email' => 'required|email|unique:users',
'phone' => 'required|min:11|numeric',
'course_id'=>'required'
]);
$user = new User();
$user->name= $request->Input(['name']);
$user->email= $request->Input(['email']);
$user->phone= $request->Input(['phone']);
$user->date = date('Y-m-d');
$user->completed_status = '0';
$user->course_id=$request->Input(['course_id']);
$user->save();
return redirect('success');
}

One possible solution would to use regex.
'phone' => 'required|regex:/(01)[0-9]{9}/'
This will check the input starts with 01 and is followed by 9 numbers. By using regex you don't need the numeric or size validation rules.
If you want to reuse this validation method else where, it would be a good idea to create your own validation rule for validating phone numbers.
Docs: Custom Validation
In your AppServiceProvider's boot method:
Validator::extend('phone_number', function($attribute, $value, $parameters)
{
return substr($value, 0, 2) == '01';
});
This will allow you to use the phone_number validation rule anywhere in your application, so your form validation could be:
'phone' => 'required|numeric|phone_number|size:11'
In your validator extension you could also check if the $value is numeric and 11 characters long.

From Laravel 5.5 on you can use an artisan command to create a new Rule which you can code regarding your requirements to decide whether it passes or fail.
Ej:
php artisan make:rule PhoneNumber
Then edit app/Rules/PhoneNumber.php, on method passes
/**
* Determine if the validation rule passes.
*
* #param string $attribute
* #param mixed $value
* #return bool
*/
public function passes($attribute, $value)
{
return preg_match('%^(?:(?:\(?(?:00|\+)([1-4]\d\d|[1-9]\d?)\)?)?[\-\.\ \\\/]?)?((?:\(?\d{1,}\)?[\-\.\ \\\/]?){0,})(?:[\-\.\ \\\/]?(?:#|ext\.?|extension|x)[\-\.\ \\\/]?(\d+))?$%i', $value) && strlen($value) >= 10;
}
Then, use this Rule as you usually would do with the validation:
use App\Rules\PhoneNumber;
$request->validate([
'name' => ['required', new PhoneNumber],
]);
docs

Validator::extend('phone', function($attribute, $value, $parameters, $validator) {
return preg_match('%^(?:(?:\(?(?:00|\+)([1-4]\d\d|[1-9]\d?)\)?)?[\-\.\ \\\/]?)?((?:\(?\d{1,}\)?[\-\.\ \\\/]?){0,})(?:[\-\.\ \\\/]?(?:#|ext\.?|extension|x)[\-\.\ \\\/]?(\d+))?$%i', $value) && strlen($value) >= 10;
});
Validator::replacer('phone', function($message, $attribute, $rule, $parameters) {
return str_replace(':attribute',$attribute, ':attribute is invalid phone number');
});
Usage
Insert this code in the app/Providers/AppServiceProvider.php to be booted up with your application.
This rule validates the telephone number against the given pattern above that i found after
long search it matches the most common mobile or telephone numbers in a lot of countries
This will allow you to use the phone validation rule anywhere in your application, so your form validation could be:
'phone' => 'required|numeric|phone'

You can use this :
'mobile_number' => ['required', 'digits:10'],

Use
required|numeric|size:11
Instead of
required|min:11|numeric

You can try out this phone validator package. Laravel Phone
Update
I recently discovered another package Lavarel Phone Validator (stuyam/laravel-phone-validator), that uses the free Twilio phone lookup service

There are a lot of things to consider when validating a phone number if you really think about it. (especially international) so using a package is better than the accepted answer by far, and if you want something simple like a regex I would suggest using something better than what #SlateEntropy suggested. (something like A comprehensive regex for phone number validation)

I used the code below, and it works
'PHONE' => 'required|regex:/(0)[0-9]/|not_regex:/[a-z]/|min:9',

$request->validate([
'phone' => 'numeric|required',
'body' => 'required',
]);

Related

Laravel, valdiation alpha_dash prevent dashes

I have validation rule:
$rules = ['username' => 'required|string|alpha_dash']
I need prevent dash in validation, allow only underscores, letters and numbers. How I can do it? Now alpha_dash allow dashes..
I would suggests to use regex validation to get more power to customize in future if you wish. SEE https://laravel.com/docs/5.8/validation#rule-regex
'regex:/^[A-Za-z0-9_]+$/'
or more specifically
$rules = ['username' => 'required|string|regex:/^[A-Za-z0-9_]+$/']
Because as per documentation alpha_dash supports-
The field under validation may have alpha-numeric characters, as well
as dashes and underscores.
You can use regex:pattern in your validation.
$rules = ['username' => 'required|string|regex:/^[A-Za-z0-9_.]+$/']
Aside from the other answers, You can create custom validation rule
following artisan command will create a new rule in the app\Rules\ folder.
php artisan make:rule AlphaNumeric
AlphaNumeric
class AlphaNumeric implements Rule
{
public function passes($attribute, $value)
{
return preg_match('/^[A-Za-z0-9_]+$/', $value);
}
public function message()
{
return 'your custom error message.';
}
}
Controller
$rules = [
'username' => ['required', 'string', new AlphaNumeric()]
]
This approach can be use to create more complex and flexible validations.
Try this rule instead of alpha_dash
[
'username' => ['regex:/^[0-9a-zA-Z_\-]*$/']
]

Laravel Validation Rules If Value Exists in Another Field Array

I am working in Laravel 5.4 and I have a slightly specific validation rules need but I think this should be easily doable without having to extend the class. Just not sure how to make this work..
What I would like to do is to make the 'music_instrument' form field mandatory if program array contains 'Music'.
I found this thread How to set require if value is chosen in another multiple choice field in validation of laravel? but it is not a solution (because it never got resolved in the first place) and the reason it doesn't work is because the submitted array indexes aren't constant (not selected check boxes aren't considered in indexing the submission result...)
My case looks like this:
<form action="" method="post">
<fieldset>
<input name="program[]" value="Anthropology" type="checkbox">Anthropology
<input name="program[]" value="Biology" type="checkbox">Biology
<input name="program[]" value="Chemistry" type="checkbox">Chemistry
<input name="program[]" value="Music" type="checkbox">Music
<input name="program[]" value="Philosophy" type="checkbox">Philosophy
<input name="program[]" value="Zombies" type="checkbox">Zombies
<input name="music_instrument" type="text" value"">
<button type="submit">Submit</button>
</fieldset>
</form>
If I select some of the options from the list of check boxes I can potentially have this result in my $request values
[program] => Array
(
[0] => Anthropology
[1] => Biology
[2] => Music
[3] => Philosophy
)
[music_instrument] => 'Guitar'
Looking at validation rules here: https://laravel.com/docs/5.4/validation#available-validation-rules I think something like his should work but i am literally getting nothing:
$validator = Validator::make($request->all(),[
'program' => 'required',
'music_instrument' => 'required_if:program,in:Music'
]);
I was hoping this would work too but no luck:
'music_instrument' => 'required_if:program,in_array:Music',
Thoughts? Suggestions?
Thank you!
Haven't tried that, but in general array fields you usually write like this: program.*, so maybe something like this will work:
$validator = Validator::make($request->all(),[
'program' => 'required',
'music_instrument' => 'required_if:program.*,in:Music'
]);
If it won't work, obviously you can do it also in the other way for example like this:
$rules = ['program' => 'required'];
if (in_array('Music', $request->input('program', []))) {
$rules['music_instrument'] = 'required';
}
$validator = Validator::make($request->all(), $rules);
I know this post is older but if someone came across this issue again.
$validator = Validator::make($request->all(),[
'program' => 'required',
'music_instrument' => 'required_if:program,Music,other values'
]);
You could create a new custom rule called required_if_array_contains like this...
In app/Providers/CustomValidatorProvider.php add a new private function:
/**
* A version of required_if that works for groups of checkboxes and multi-selects
*/
private function required_if_array_contains(): void
{
$this->app['validator']->extend('required_if_array_contains',
function ($attribute, $value, $parameters, Validator $validator){
// The first item in the array of parameters is the field that we take the value from
$valueField = array_shift($parameters);
$valueFieldValues = Input::get($valueField);
if (is_null($valueFieldValues)) {
return true;
}
foreach ($parameters as $parameter) {
if (in_array($parameter, $valueFieldValues) && strlen(trim($value)) == 0) {
// As soon as we find one of the parameters has been selected, we reject if field is empty
$validator->addReplacer('required_if_array_contains', function($message) use ($parameter) {
return str_replace(':value', $parameter, $message);
});
return false;
}
}
// If we've managed to get this far, none of the parameters were selected so it must be valid
return true;
});
}
And don't forget to check there is a use statement at the top of CustomValidatorProvider.php for our use of Validator as an argument in our new method:
...
use Illuminate\Validation\Validator;
Then in the boot() method of CustomValidatorProvider.php call your new private method:
public function boot()
{
...
$this->required_if_array_contains();
}
Then teach Laravel to write the validation message in a human-friendly way by adding a new item to the array in resources/lang/en/validation.php:
return [
...
'required_if_array_contains' => ':attribute must be provided when ":value" is selected.',
]
Now you can write validation rules like this:
public function rules()
{
return [
"animals": "required",
"animals-other": "required_if_array_contains:animals,other-mamal,other-reptile",
];
}
In the above example, animals is a group of checkboxes and animals-other is a text input that is only required if the other-mamal or other-reptile value has been checked.
This would also work for a select input with multiple selection enabled or any input that results in an array of values in one of the inputs in the request.
The approach I took for a similar problem was to make a private function inside my Controller class and use a ternary expression to add the required field if it came back true.
I have roughly 20 fields that have a checkbox to enable the input fields in this case, so it may be overkill in comparison, but as your needs grow, it could prove helpful.
/**
* Check if the parameterized value is in the submitted list of programs
*
* #param Request $request
* #param string $value
*/
private function _checkProgram(Request $request, string $value)
{
if ($request->has('program')) {
return in_array($value, $request->input('program'));
}
return false;
}
Using this function, you can apply the same logic if you have other fields for your other programs as well.
Then in the store function:
public function store(Request $request)
{
$this->validate(request(), [
// ... your other validation here
'music_instrument' => ''.($this->_checkProgram($request, 'music') ? 'required' : '').'',
// or if you have some other validation like max value, just remember to add the |-delimiter:
'music_instrument' => 'max:64'.($this->_checkProgram($request, 'music') ? '|required' : '').'',
]);
// rest of your store function
}
Here my piece of code to solve that kind of trouble usind Laravel 6 Validation Rules
I tried to use the code above
public function rules()
{
return [
"some_array_field.*" => ["required", "integer", "in:1,2,4,5"],
"another_field" => ["nullable", "required_if:operacao.*,in:1"],
];
}
I need that when some_array_field has 1 in your value, another_field must be validated, otherwhise, can be null.
With the code above, doesn't work, even with required_if:operacao.*,1
If I change the rule for another_field to required_if:operacao.0,1 WORKS but only if the value to find is in index 0, when the order changes, validation fails.
So, I decided to use a custom closure function
Here's the final code for the example that works fine form me.
public function rules()
{
return [
"some_array_field.*" => ["required", "integer", "in:1,2,4,5"],
"another_field" => [
"nullable",
Rule::requiredIf (
function () {
return in_array(1, (array)$this->request->get("some_array_field"));
}
),
]
];
}
I hope that solve your trouble too!

Conditional form validation in CakePHP 3

I want to validate some fields from validationDefault() function not all because of conditions but did not find any solution.
Example:
public function validationDefault(Validator $validator) {
$validator
->requirePresence('title', 'create')
->notEmpty('title');
$validator
->requirePresence('inquiry')
->allowEmpty('inquiry');
$validator
->requirePresence('dosage')
->allowEmpty('dosage');
$validator
->requirePresence('dosage_occurance')
->integer('dosage_occurance')
->allowEmpty('dosage_occurance');
return $validator;
}
Note: Response coming from two diffrent form first contains(title and inquiry) other contains(title, dosage and dosage_occurance).
I want to validate it from validationDefault() but it give me error
"dosage_occurance": {
"_required": "This field is required"
}
when I am not sending dosage_occurance which is correct but according to condition it is wrong.
using fieldList while creating new entity but it is not working.
Thanks
You want conditional validation.
Taken from the documentation:
When defining validation rules, you can use the on key to define when a validation rule should be applied. If left undefined, the rule will always be applied. Other valid values are create and update. Using one of these values will make the rule apply to only create or update operations.
Read the whole documentation page.
Example taken from there, pay attention to the on part.
$validator->add('picture', 'file', [
'rule' => ['mimeType', ['image/jpeg', 'image/png']],
'on' => function ($context) {
return !empty($context['data']['show_profile_picture']);
}
]);

How to modify Laravel 5 default authentication system

I am using the default Laravel 5 authentication system. I would like to simply add a check that verifies that the user is using a school email account (I am writing this for my University). So for example I want to make sure they are using #harvard.edu, and not #gmail.com. If they are not using the correct email type, I want to add an error to the $errors variable, and print that along with the the other possible errors on the registration form.
It appears that the actual validation occurs in Registrar.php. I am assuming I will have to add something to the email portion of the validator function.
public function validator(array $data)
{
return Validator::make($data, [
'name' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|confirmed|min:6',
]);
}
The other part I am confused about is where the actually error messages are located.
I am new to Laravel, thanks in advance.
To add a custom validation, you can read the documentation at http://laravel.com/docs/5.0/validation#custom-validation-rules . For example, in you case:
Validator::extend('email_harvard', function($attribute, $value, $parameters)
{
$segments = explode("#", $value, 2);
return end($segments) == "harvard.com";
});
After that, modify your validator rules, change the line:
'email' => 'required|email|max:255|unique:users',
to be:
'email' => 'required|email|email_harvard|max:255|unique:users',
About the error messages, you can read here. In Laravel 5, the validation messages are located at resources/lang/xx/validation.php where xx is the language code.

how to make an input date field greater than or equal to another date field using validation in laravel

Hi iam developing an application using laravel is there any way to make an input date field greater than or equal to another date field using validation.
I know that i can achieve this through jquery and i have already got that working, but i want to know whether is this achievable through laravel validation since laravel has got some predefined validations.
For Example
protected $validationRules = array
(
'a' => 'date',
'b' => 'date|(some validation so that the b value is greater than or equal to that of 'a')'
);
EDIT
If there is any other approach to solve the problem using laravel concept please tell me
I tried
Validator::extend('val_date', function ($attribute,$value,$parameters) {
return preg_match("between [start date] and DateAdd("d", 1, [end date])",$value);
});
Thanks in advance
I had the same problem. before and after does not work when dates could be the same. Here is my short solution:
NOTE: Laravel 5.3.25 and later have new built in rules: before_or_equal and after_or_equal
// 5.1 or newer
Validator::extend('before_or_equal', function($attribute, $value, $parameters, $validator) {
return strtotime($validator->getData()[$parameters[0]]) >= strtotime($value);
});
// 5.0 & 4.2
Validator::extend('before_or_equal', function($attribute, $value, $parameters) {
return strtotime(Input::get($parameters[0])) >= strtotime($value);
});
$rules = array(
'start'=>'required|date|before_or_equal:stop',
'stop'=>'required|date',
);
Emil Aspman's answer is correct, but doesn't work for Laravel 5.2. this solution works for Laravel 5.2:
Validator::extend('before_equal', function($attribute, $value, $parameters, $validator) {
return strtotime($validator->getData()[$parameters[0]]) >= strtotime($value);
});
Yes, you can use after:date or before:date like this:
protected $rules = array(
'date' => 'after:'.$yourDate
);
or alternatively
protected $rules = array(
'date' => 'before:'.$yourDate
);
It will do exactly what you described. Also check out the official documentation.
You can also specify rules of your own using custom validation rules.
The proper solution would be if you extended the Validator with your own rule. A simple example from the docs:
Validator::extend('foo', function($attribute, $value, $parameters)
{
return $value == 'foo';
});
Read more here

Categories