Laravel validation username must not start with specific string - php

I want to register user but I want to put validation rule on username that username should not start with special characters and also should not start with web. I found regex that work fine special characters but detect the string it give me error of Invalid format
return [
'username' => [
'required',
'regex:/^\S*$/u',
'regex:/^[_]?[a-zA-Z0-9]+([_.-]?[a-zA-Z0-9])*$/',
'unique:users'
],
'full_name' => 'required',
];

Try this?
return [
'username' => [
'required|
not_regex:/^[web_-][a-z_\-0-9]*/i|
regex:/^[A-Za-z_ \-0-9]+$/u|
unique:users'
],
'full_name' => 'required',
];

This should work as you want it to
return [
'username' => [
'required',
'regex:/^(?!web)[a-zA-Z]\w+$/',
'unique:users'
],
'full_name' => 'required',
];
Here's a regex101 demo for you to test it out.

Related

Unique field validation issue in laravel

I'm trying to validate a unique entry in my laravel app
following is my validation array,
$website = $websiteModel->find($id);
$this->validate($request, [
'subDomainName' => ['required','regex:/^[A-Za-z0-9 ]+$/'],
'subDomainSuffix' => ['required'],
'packageType' => ['required'],
'themeid' => ['required'],
'lang' => ['required'],
'user' => ['required'],
'domain' => [
'required',
'string',
'min:2',
'max:255',
Rule::unique('apps')->ignore($website)
],
], $request->all());
My validation working properly BUT,
When i tried to enter a duplicate value for my domain field, It get validated properly but not showing the error message, saying sorry the name is already exists...
<input type="text" id="domain" class="form-control" name="domain" >
{!! $errors->first('domain', '<span class="help-block" role="alert">:message</span>') !!}
Here in this span it shows nothing but in the common error message area it shows sorry the form cannot be updated... So how can I validate the field properly and display the relevant error message
Do something like this:
On insert request use
'domain' => [
...
'unique:websites,domain'
]
On update request use
'domain' => [
...
"unique:websites,domain,{$this->website->id}"
]
Or
'domain' => [
...
Rule::unique('websites', 'domain')->ignore($this->website)
]
You passed $request->all() as validation messages.
Please Try:
$website = $websiteModel->find($id);
$request->validate([
'subDomainName' => ['required','regex:/^[A-Za-z0-9 ]+$/'],
'subDomainSuffix' => ['required'],
'packageType' => ['required'],
'themeid' => ['required'],
'lang' => ['required'],
'user' => ['required'],
'domain' => [
'required',
'string',
'min:2',
'max:255',
Rule::unique('apps')->ignore($website)
],
]);
don't you need to pass duplicate column in ignore Rule To instruct the validator to ignore the website domain, except for it self ? for example like
Rule::unique('apps')->ignore($website->id)
please try this one . it helps to solve your problem
use exception and validator in top of the file
use Exception;
use Validator;
$rules = [
'subDomainName' => 'required|unique:sub_domain_name',
];
$validator = Validator::make($request->all(), $rules, $message);
if ($validator->fails()) {
throw new Exception(implode('\n', $validator->errors()->all()));
}
sub_domain_name : this is database column name

Laravel 5.4 sometimes|required validation not raising on "null" input

I'm having a problem validating inputs that are only going to be present sometimes in the Request.
// Controller
public function update(Request $request, User $user)
{
$updateResult = $user->updateUser($request);
return dd($updateResult);
}
// User Model
protected $validation = [
'rules' => [
'email' => [
'sometimes',
'email',
'required',
],
'password' => [
'sometimes',
'min:6',
'required',
],
'first_name' => [
'sometimes',
'required',
],
'last_name' => [
'sometimes',
'required',
],
],
'messages' => [
'email.required' => 'An email is required.',
'email.email' => 'The email must be valid.',
'password.required' => 'A password is required.',
'password.min' => 'Your password must be at least six (6) characters long.',
'first_name.required' => 'Your first name is required.',
'last_name.required' => 'Your last name is required.',
],
];
public function updateUser(Request $request)
{
$validation = Validator::make($request->all(), [
$this->validation['rules'],
$this->validation['messages'],
]);
if ($validation->fails())
{
return $validation;
}
else
{
return "OK";
}
}
So in some update pages $request->all() is only going to have a subset of these fields. However, even a field is present, but the value is null, the required doesn't trigger.
[
'first_name' => null,
'last_name' => 'Davidson',
'job_title' => 'Tech Support',
]
The above request array will return "OK"... If I remove sometimes from the fields, then when a partial input request is sent, it fails saying the fields are required.
I am clearing missing something here, but from reading the docs I thought I'd configured this correctly:
In some situations, you may wish to run validation checks against a
field only if that field is present in the input array. To quickly
accomplish this, add the sometimes rule to your rule list:
$v = Validator::make($data, [
'email' => 'sometimes|required|email', ]);
The problem you are facing is simply due to an error in your call to the validator. The second parameter is not a multidimensional array as you passed. The rules array and the messages array are separate parameters.
$validation = Validator::make($request->all(), [
$this->validation['rules'],
$this->validation['messages'],
]);
Should be replaced by
$validation = Validator::make($request->all(),
$this->validation['rules'], $this->validation['messages']);
In Laravel 5.4 empty strings are converted to Null by the ConvertEmptyStringsToNull middleware... that might cause you some issues...
You should add nullable to all your optional validations...
Hope this helps
'first_name' => [
'sometimes',
'required',
],
Will never work as expected. Sometimes indicates: if something comes, what is the next rule? In this case 'required'. Required what? Change this to:
'first_name' => [
'sometimes',
'required',
'min:1',
],
The null value will still be a null value if no input is given and won't fail. If you want to keep the value of the field in the table for updates, populate the input in the form with it's respected values.
The null value was send as '' and got nulled by the ConvertEmptyStringsToNull::class in the app\Http\kernel.php middleware.

Testing register form fails with password confirmation with Laravel 5

I'm trying to test my register form.
I wrote this test :
public function testUserRegistration()
{
$response = $this->call('POST', 'auth/register', array(
'_token' => csrf_token(),
'name' => 'toni',
'username' => 'toni#free.fr',
'password' => 'toni19'
));
// Error The given data failed to pass validation.
$this->assertEquals(200, $response->getStatusCode());
}
When I run this test, it fails with following error :
Error The given data failed to pass validation.
And my controller code :
$this->validate($request, [
'name' => 'required|unique:users',
'username' => 'required|unique:users,username|email|min:3',
'password' => 'required|confirmed|min:5'
], User::getFormMessages());
Thanks for your help.
I think you miss one input like:
$response = $this->call('POST', 'auth/register', array(
'_token' => csrf_token(),
'name' => 'toni',
'username' => 'toni#free.fr',
'password' => 'toni19'
'password_confirmation' => 'toni19'
));
And validator:
$this->validate($request, [
'name' => 'required|unique:users',
'username' => 'required|unique:users,username|email|min:3',
'password' => 'required|min:5|confirmed',
'password_confirmation' => 'required|min:5|same:password'
], User::getFormMessages());
From Laravel docs:
confirmed
The field under validation must have a matching field of
foo_confirmation. For example, if the field under validation is
password, a matching password_confirmation field must be present in
the input.

Laravel 5.3 check if email exists only if password field is filled in

My application uses the standard validator, and my form makes the user provide an email address. They may continue as a guest, but if they do want to create an account; the only thing they will have to provide is a password and in combination with that email address will create the user account.
However, my issue is I am not sure how to use the validator exists only if the password field has been filled in.
$this->validate($request, [
'first_name' => 'required',
'email' => 'required|confirmed|email',
'last_name' => 'required',
'street_1' => 'required',
'zip_code' => 'required',
'phone_1' => 'required',
'password' => 'required_if:account,1|confirmed',
]);
I could do a check and return redirect with an error message, but I'd prefer to go through the validator if I can.
The simplest solution is to put your validation rules into an array then perform your desired check. So if the user checked the "account creation" checkbox, add the rules.
$rules = [
'first_name' => 'required',
'last_name' => 'required',
'street_1' => 'required',
'zip_code' => 'required',
'phone_1' => 'required',
'password' => 'required_if:account,1|confirmed',
]
if ($request->input('acount') == 1) {
$rules['email'] = 'required|confirmed|email'
}

Validiation check in Laravel php

I'm trying to write a validation check in PHP Laravel for a username field with the functionality to let the user know what went wrong. I have a couple of if statements with regular expression checks but it won't work. The requirements of the regular expression are: can't start with a ".", No more than 1 "." in a row, No capitals, Only a-z, No special characters. So for example like this "user.name" would be valid, but things like "username." or ".username" would all be invalid.
So far I got this:
$oValidator = Validator::make(Input::all(), [
'username' => 'required|regex:/^[a-zA-Z0-9][\w\.]+[a-zA-Z0-9]$/',
'username' => 'required',
'password' => 'required',
'firstname' => 'required',
'lastname' => 'required',
'email' => 'required|email'
]);
I want to give feedback for the mistakes that user makes, example: user input is ".username", program feedback should be "Dot in front of string is not allowed".
All you have to do is to include a custom message for your validation.
$this->validate($request, [
'username' => 'required|regex:/^[a-zA-Z0-9][\w\.]+[a-zA-Z0-9]$/',
], ['regex' => 'Username cannot start with period(.), etc...]);
Your code should look like this. Please remember regex custom message will apply too all of these fields instead of just username so I would separate username validation like above.
$oValidator = Validator::make(Input::all(), [
'username' => 'required|regex:/^[a-zA-Z0-9][\w\.]+[a-zA-Z0-9]$/',
'username' => 'required',
'password' => 'required',
'firstname' => 'required',
'lastname' => 'required',
'email' => 'required|email'
], ['regex' => 'Username cannot start with period, etc...']);

Categories