Validate if input is url or email in Laravel 9 - laravel

I am trying to validate a field but I am not able to do it.
I have this Request Validator
public function rules()
{
return [
...
'input' => 'required|url|email',
];
}
What I want to do is to validate if the input is url or email, can be one of them, what can I do? Here I am validating both cases, but the input can be one of them. Thanks.

public function rules(): array
{
return [
'input' => ['required', function ($field, $value) {
$data = [$field => $value];
$emailValidator = Validator::make($data, [$field => 'email']);
$urlValidator = Validator::make($data, [$field => 'url']);
if ($urlValidator->passes() || $emailValidator->passes()) {
return true;
}
$this->validator->getMessageBag()->add($field, $field . ' must be a valid email address or a valid url');
return false;
}],
];
}

Related

How to Validate JSON Input using Requests? Laravel

I am sending some data with formData, and for one fields (object) I use: JSON.stringify(this.allValues).
and I try to validate all values from this.allValues .
Till now I tried 2 methods from here , now I try with the second one with "JsonApiMiddleware" .
But with this I validation(required) errors, even if the fields are not null.
public function rules()
{
$newValues = json_decode(request()->get('all_values')); // Here I have all values that needs to be validated
dd($newValues); // I post the respons for this below
$newValues = [
'saleforce_id' => 'required',
'customer_id' => 'required',
]
return $newValues;
}
""customer_id":49,"saleforce_id":"","lkp_invoicing_method_id":3,"lkp_product_category_id":10,"lkp_notice_period_id":5,"lkp_licence_term_id":9,"is_attrition_risk":false,"is_additional_users":false,"contract_value_exc_vat_annual":"257590...and many more
Treat the JSON object you send as a php associative array. For example let's say your sent data looks like this.
/* var allValues = */
{
data: {
requiredField1: value,
requiredField2: value,
requiredArrayField1: [
1,
2,
3,
],
optionalField1: value
}
}
Then, you can validate the data like this:
public function rules()
{
return: [
'data' => 'required|array',
'data.requiredField1' => 'required',
'data.requiredField2' => 'required',
'data.requiredArrayField1' => 'required|array',
'data.requiredArrayField1.*' => 'required|numeric',
'data.optionalField1' => 'nullable',
];
}
I found a solution.
I use the method from laracast, fureszpeter, method with middleware, and I edit it.
public function handle($request, Closure $next)
{
if ($request->has('all_values')) {
$request->merge([
'all_values' => json_decode($request->get('all_values'), true)
]);
} // only when I have all_values in my request
return $next($request);
}
}
In my existing Request:
public function rules()
{
$newValues = [
'all_values.saleforce_id' => 'required'
'all_values.customer_id' => 'required',
// and the rest of the files
]
return $newValues
}

Validation in Laravel. How to transfer the rule and message to the controller?

I am having problems displaying custom error messages.
I received a training project that had the following code:
class StoreProject extends FormRequest
{
public function authorize()
{
return true;
}
public function rules()
{
return [
'name' => 'required|unique:projects,name|max:255',
'website' => 'url',
];
}
public function messages()
{
return [
'name' => 'Це імʼя вже використовується',
'website' => 'Будь-ласка введіть адресу вашого сайту вірно http://...'
];
}
}
I added the function message( ) myself.
This is the controller code:
public function store(StoreProject $request)
{
$project = new Project($request->except('project_image'));
$project->owner_id = Auth::user()->id;
$project->status_id = StatusProject::UNCONFIRMED;
//send email to moderator and accountant for the moderation
if( $project->save() ) {
$this->dispatch(new ConfirmNewProject($project));
}
// load image from cropie serves
if ($request->has('project_image')) {
$file = self::croppie($request->input("project_image"));
$project->uploadImage($file, 1);
}
return redirect()->route('projects.show', [$project->id]);
}
I tried various methods: withErrors([]) and this method:
'custom' => [
'attribute-name' => [
'rule-name' => 'custom-message',
'name' => 'Це імʼя вже використовується',
'website' => 'Будь-ласка введіть адресу вашого сайту вірно http://...'
],
]
but when checking, I get the key value, not the text of the error message
Errors:
validation.unique
validation.url
How to transfer the rule and message to the controller?
Try to modify the messages() function like that one:
public function messages()
{
return [
'name.required' => 'Name required message',
'name.unique' => 'Name unique message',
'name.max' => 'Name max message',
'website.url' => 'Будь-ласка введіть адресу вашого сайту вірно http://...'
];
}

Laravel custom error message from inside custom validator function using $validator->errors->add()

I have custom validation rule appointment_status. I am performing various test cases on it and decide what error message is best and throwback. it will be different for every case. I want the $validator->errors()->add('status', __('Invalid status for an appointment in past') to set the error message and it's adding. but it's not returning back to the controller. I can't access this message anywhere. it shows only the status.appointment_status one which is set in messages() function.
Custom Request class:
namespace Modules\ShopManager\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class AppointmentsRequest extends FormRequest
{
public function __construct()
{
\Validator::extend('appointment_status', 'Modules\ShopManager\Validators\CustomValidator#appointmentStatus');
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
$rules = [
'services' => 'required',
'sdate' => 'required|date_format:m-d-Y|time_range:sTime,edate,eTime,timezone',
'edate' => 'required|date_format:m-d-Y|workinghours_range:sdate,sTime,edate,eTime,timezone',
'sTime' => 'required|date_format:h:i a',
'eTime' => 'required|date_format:h:i a',
'cname' => 'required',
'cphone' => 'required_without:cemail',
'cemail' => 'nullable|required_without:cphone|email',
'timezone' => 'required',
'status' => 'required|appointment_status:sdate,sTime,edate,eTime,timezone',
];
return $rules;
}
public function messages()
{
return [
'status.appointment_status' => 'Invalid status'
];
}
public function attributes()
{
return [
'services' => 'Services',
'date' => 'Date',
'sTime' => 'Start Time',
'eTime' => 'End Time',
'cname' => 'Customer name',
'cphone' => 'Customer phone',
'cemail' => 'Customer email',
'internal_note' => 'Internal note',
'status' => 'Status',
];
}
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
}
The custom validator function:
public function appointmentStatus($attribute, $value, $parameters, $validator)
{
$dateTimeOperations = new DateTimeOperations;
$sdate = array_get($validator->getData(), $parameters[0]);
$startTime = array_get($validator->getData(), $parameters[1]);
$edate = array_get($validator->getData(), $parameters[2]);
$endTime = array_get($validator->getData(), $parameters[3]);
$timezone = array_get($validator->getData(), $parameters[4]);
$now = $dateTimeOperations->getNow($timezone);
$start = $dateTimeOperations->getTimestamp($sdate, $startTime, $timezone);
$end = $dateTimeOperations->getTimestamp($edate, $endTime, $timezone);
switch ($value) {
case constants('appointments.status.pendig'):
$start->lessThan($now)
? $validator->errors()->add('status', __('Invalid status for an appointment in past'))
: '';
}
return $validator->errors()->any();
}
Adding an error just to the field without specifying the rule I don't think will work, that's why the message from the validation request takes precedence.
So change it to this:
$validator->errors()->add('status.appointment_status', __('Invalid status for an appointment in past'))
And also in your case do you maybe have a typo: pendig to be pending?
You have to create custom validator rules and add below code inside your rule wherever required, See example below:
$validator->after(function ($validator) {
if ($this->somethingElseIsInvalid()) {
$validator->errors()->add('field', 'Something is wrong with this field!');
}
});

How to use unique validation in Yii 2

I want to make usernames and email addresses unique.
I am using yii base to develop my App. It doesnt not work for me.
My Model:
public function rules()
{
return [
[['username', 'email', 'password'], 'required'],
[['username', 'email'], 'unique']
];
}
My Controller:
public function actionCreate()
{
$model = new Userapp();
$post = Yii::$app->request->post('UserApp');
if (Yii::$app->request->isPost && $model->validate()) {
$model->email = $post['email'];
$model->username = $post['username'];
$model->password = $model->setPassword($post['password']);
if($model->save()){
return $this->redirect(['view', 'id' => $model->id]);
}
}
return $this->render('create', [
'model' => $model,
]);
}
Yii2 has a bunch of built in validators see.
One of which is unique
From Yii2 docs.
// a1 needs to be unique in the column represented by the "a1" attribute
['a1', 'unique'],
// a1 needs to be unique, but column a2 will be used to check the uniqueness
of the a1 value
['a1', 'unique', 'targetAttribute' => 'a2'],
Update:
In your rules array, add the unique validator to email and username like so:
public function rules()
{
return [
[['username', 'email', 'password'], 'required'],
[['username', 'email'], 'unique'],
];
}
Then before saving the model:
if(!$model->validate()){
return false;
}
Update 2:
You are trying to validate the model before any attributes have been assigned. Update your controller code to the following:
public function actionCreate()
{
$model = new Userapp();
$post = Yii::$app->request->post('UserApp');
if (Yii::$app->request->isPost) {
$model->email = $post['email'];
$model->username = $post['username'];
$model->password = $model->setPassword($post['password']);
if($model->validate() && $model->save()){
return $this->redirect(['view', 'id' => $model->id]);
}
else {
return false;
}
}
return $this->render('create', [
'model' => $model,
]);
}
the idea was to do a re-direction only when $model->save() is true otherwise render back the original model to be created/updated

Problems creating users in laravel

I am creating the traditional register of users with Laravel and I have a problem to send specific value.
public function postUserRegister(){
$input = Input::all();
$rules = array(
'name' => 'required',
);
$v = Validator::make($input, $rules);
if($v->passes() ) {
$user = User::create(Input::all());
} else {
Session::flash('msg', 'The information is wrong');
return Redirect::back();
}
}
This code works correctly , but I need to send always the same value into table users and this column doesn't appear in the form. How can I send the value of the table if the value doesn't appear?
You can just supply the value manually. There are several ways to do this, here is one:
$user = new User(Input::all());
$user->yourcolumn = $yourdata;
$user->save();
You can use input merge to add extra fields.
Input::merge(array('val_key' => $val_name));
$input = Input::all();
Firstly, I think it would be ideal to clean a bit the method, something like that:
public function postUserRegister(Request $request)
{
$validator = Validator::make($request->all(), [
'name' => 'required'
]);
if ($v->fails()) {
Session::flash('msg', 'The information is wrong');
}
User::create($request->all());
return Redirect::back();
}
And now you can simply assign a data to a specific column by using:
$request->merge(['column_name' => 'data']);
The data can be null, or variable etc. And now the whole code would look something like:
public function postUserRegister(Request $request)
{
$request->merge(['column_name' => 'data']);
$validator = Validator::make($request->all(), [
'name' => 'required'
]);
if ($validator->fails()) {
Session::flash('msg', 'The information is wrong');
}
User::create($request->all());
return Redirect::back();
}
You can add whatever data you want directly into the create method:
public function postUserRegister()
{
$input = request()->all();
if (validator($input, ['name' => 'required'])->fails()) {
return back()->with('msg', 'The information is wrong');
}
$user = User::create($input + ['custom' => 'data']);
//
}
P.S. Merging that data into the request itself is a bad idea.
You can do this in the User model by adding the boot() method.
class User extends Model
{
public static function boot()
{
parent::boot();
static::creating(function ($user) {
$user->newColumn = 'some-value';
});
}
...
}
Reference: https://laravel.com/docs/5.2/eloquent#events

Resources