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.
Related
I am doing validation this way.
$rules = [
'email'=> 'required|regex:/^.+#.+$/i|unique:tab_example,email,'.$this>get('example_id').',example_id'
];
return $rules;
However, I am not getting success.
The error informs that
the email already exists
What I want is that if the email already exists and is from the same user does not need to inform that the email already exists.
I do not know what the problem is in my code.
You can use
'email' => "required|email|unique:users,email,{$id},id",
The id should be replaced with the primary key column name of the table you use for the unique check. The {$id} should be defined before $rules array like:
$id = $request->route('user')
Sometimes, you may wish to ignore a given ID during the unique check.
For example, consider an "update profile" screen that includes the user name, e-mail address, and location. Of course, you will want to verify that the e-mail address is unique.
However, if the user only changes the name field and not the e-mail field, you do not want a validation error to be thrown because the user is already the owner of the e-mail address.
you can use like:
'email' => [
'required',
Rule::unique('users')->ignore($user->id),
],
Try this
'email' => Rule::unique('users')->ignore($user->id, 'user_id');
Read Under the Section Forcing A Unique Rule To ignore A given Field
Try This way
$rules = [
'email'=> ['required', 'email', \Illuminate\Validation\Rule::unique('tab_example', 'email')->whereNot('example_id',$this->get('example_id'))]
];
Just use
$this->route('example_id')
instead of
$this>get('example_id')
And if you use resource route then use $this->route('user').
$rules = [
'email'=> 'required|regex:/^.+#.+$/i|unique:tab_example,email,'.$this->route('example_id').',example_id'
];
return $rules;
Playing around with a referral system in laravel 5.4. I have been able to create a unique shareable link for each user.
When another user clicks on that, I want the portion of the url with the referral id of the link's original owner to be added to the referrer field of the user.
I tried this method and been getting this error, what better way is there to do this.
use Illuminate\Support\Facades\Input;
protected function create(array $data)
{
$ref = Input::get('ref');
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
'referrer' => $ref
]);
return $user;
}
I am getting an error complaining that the referrer column cannot be null even though there is a ref on the link.
Sample link.
http://localhost:8000/register?ref=1b0a6294-043d-11e7-86bf-56847afe9799
User Model
protected $fillable = [
'name', 'email', 'password', 'level', 'btc_address', 'referrer'
];`
I think the problem might be your routes and url you use in form for registering user.
The url you showed is probably for displaying registration form, but when you send the form, you send it to http://localhost:8000/register url so you don't have ref defined in your url.
You should make sure, that you send form also to http://localhost:8000/register?ref=1b0a6294-043d-11e7-86bf-56847afe9799 url or put hidden field with ref value from get action.
Take a scenario,
There are 2 fields available in the form.
1) input type file for manual upload.
2) input type = text to enter youtube video url.
is it possible using laravel built-in validations so that validation will be fired if user has left both fields empty!
I have gone through https://laravel.com/docs/5.3/validation but could not find what I wanted.
In your controller, you could do something like this:
$validator = Validator::make($request->all(), [
'link_upload' => 'required|etc|...',
]);
$validator2 = Validator::make($request->all(), [
'file_upload' => 'required|etc|...',
]);
if ($validator->fails() && $validator2->fails()) {
// return with errors
}
Try required-without-all validation rule. As given in documentation:
The field under validation must be present only when the all of the other specified fields are not present.
Assuming your fields name are url and file, your rule would be like below:
$rules = [
'url' => 'required_without_all:file',
'file' => 'required_without_all:url'
];
required_without:foo,bar,...
The field under validation must be present and not empty only when any of the other specified fields are not present.
Try this,
In youre update method add this
$this->validate($request, [
'fileName'=>'required',
'urlName'=>'required'
]);
dont forget to set the fillable in your model
protected $fillable = ['fileName','urlName'];
Hope this helps
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',
]);
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'
]
);
}