Laravel, valdiation alpha_dash prevent dashes - php

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_\-]*$/']
]

Related

Custom rule for validation laravel

I have made a custom rule to validate mobile no. with specific pattern and requirement.
Pattern
[0-9]{3}-[0-9]{4}-[0-9]{4}
The first three digits should be one of the following numbers:
010, 020, 030, 040, 050, 060, 070, 080, 090
Below is my code for custom rule.
App/Rules/MobileNumber.php
public function passes($attribute, $value)
{
$pattern = "/^\[0-9]{4}-[0-9]{4}-[0-9]{3}$/";
return preg_match($pattern, $value);
}
My custom validator:
app/HTTP/Request/UserRequest.php
use App\Rules\MobileNumber;
......
//manipulate data before validation
public function validationData()
{
$this->merge([
'tel_number' => $this->tel_number_1.'-'. $this->tel_number_2.'-'.$this->tel_number_3,
]);
}
public function rules()
{
return [
//other rules here....
'mob_number' => 'required', new MobileNumber()
];
}
But with the above code the validation is not working.tel_number is not reaching to passes method to check for validation.
I.E If user gives alphabetic char or symbols they are being forwarded for database save method.
So I cannot check if my regex is correct or not.
It would be very helpful if someone could highlight the mistake I've made here. Also confirm if my regex is correct to pass the validation.
I can only answer the last point for the regex validation.
You switched the order in the implementation to 4-4-3 instead of 3-4-4 digits.
The sequences 010, 020, 030, 040, 050, 060, 070, 080, 090 can be matched using 0[1-9]0 and you should not escape the \[ or else you will match it literally.
The updated code might look like:
$pattern = "/^0[1-9]0-\d{4}-\d{4}$/";

Laravel Validation: Second rule does not run

I have this validation in my controller:
$rules = [
'participants' => 'required|atleast_one'
];
Validator::extendImplicit('atleast_one', function ($attribute, $value, $parameters, $validator) {
// Long conditions.
// Returns true or false
});
$error = Validator::make($request->all(), $rules);
The second rule atleast_one is a custom rule using the extend method.
I tested this rule alone and it works. But why is it when I put the two rules together ('participants' => 'required|atleast_one'), the second one doesn't work? I tried rearranging it and still the same, the second rule doesn't work. Did I miss something on the Laravel documentation?

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

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',
]);

Unique validation across two fields

I'm building a website in Laravel 5 where a user can create a character by choosing a first name and a last name.
I've built some validation rules in around this, but am a little stumped on implementing unique validation as I need it to validate their full name, which is across two columns in my database. For example, a user can create a character called "Jon Snow", but the validation would need to check that the combination of those two fields was unique as someone else may want to create the character "Jon Doe".
I realise now whilst I write this that I could just combine the two columns in to one, and then have validation working on that.
But before I go down that route, is there any way to run validation across two fields like I need?
Below is my validation:
public function store(Request $request)
{
$character = new Characters;
$validator = Validator::make($request->all(), [
'firstname' => 'required|between:2,15',
'lastname' => 'required|between:2,15',
], [
'firstname.required' => 'You need to provide a first name!',
'lastname.required' => 'You need to provide a last name!',
'firstname.between' => 'The first name must be between :min - :max characters long.',
'lastname.between' => 'The last name must be between :min - :max characters long.',
]);
Have a look at this package felixkiss/uniquewith-validator. It contains a variant of the validateUnique rule for Laravel, that allows for validation of multi-column UNIQUE indexes.
just an idea, after validation,
$firstName = Input::get('firstname');
$lastName = Input::get('lastname');
$whereStatement = ['firstname' => $firstName, 'lastname' => $lastname];
Now use query
$user = DB::table('yourtablename')->where($whereStatement)->count()
if ($user > 1){
//then redirect back user saying the name must be uniqe
}
else{
//save data to database
}

Laravel rule for unique excluding blank or null

I have a user model that needs to have unique email addresses but I also want to allow them to be left blank in case the user has no email...I see in docs there is a way to make a rule for unique and an exception for an id...but I'm not sure how to make this allow null or blank but unique if it is not. Sorry seems like this is simple but I can't think of the answer.
public static $adminrules =
'email' => 'email|unique:users,email,null,id,email,NOT_EMPTY'
);
Edit It may be that using the rule without required is enough since a blank or null would pass validation in those cases. I might have a related bug that making it so I can't add more than 1 blank email, so I can't verify this.
public static $adminrules =
'email' => 'email|unique:users'
);
I tried this. Adding 'nullable' before 'sometimes'.
$validator = Validator::make($request->all(), [
'email' => 'nullable|sometimes|unique:users',
]);
You should try this:
$v->sometimes('email', 'email|unique:users,email', function($input)
{
return !empty($input->email);
});
$v is your validator object and you basically say that in case the email field is not empty it should also be unique (there shouldn't be a users table record with this value in email column).
In your Requests/UserRequest you'd have something like
public function rules()
{
return [
'email' => [
'nullable',Rule::unique((new User)->getTable())->ignore($this->route()->user->id ?? null)
]
];
}
The usage of nullable is what allows the field to be nullable. The other part is to check if the email is unique in the User model table.
If you wish to validate if the field is unique
between two fields please refer to this answer.
in another table, then add the following to your rules
'exists:'.(new ModelName)->getTable().',id'
You should try to change your structure of database to make the field email is nullable. And in the rules try this :
$this->validate($request,
[
'email' => 'email',
]
);
if(isset($request->address))
{
$this->validate($request,
[
'email' => 'email|unique:users'
]
);
}

Categories