I am not able to validate value in model. I am newbie in this can anyone suggest what am I doing wrong. I am working on REST API with excel file upload and validating single row at a time
Here is my data and load data in model
$data = array(
'firstName' => 'asdjqkw',
'lastName' => '',
'email' => 'ansm#',
'companyName' => 'ddq',
'address_1' => '',
'address_2' => 'aas',
'country' => '',
'state' => 'New Brunswick',
'city' => '87875',
'zip' => '484527',
);
$model->load($data);
if (!$model->validate()) {
$validation = $model->errors;
}
And here is my model rules and attribute labels as I defined required, email and maxlength validation in it but still some values is available still it is sending required validation error for that field
public function rules() {
return [
[['firstName', 'lastName', 'email', 'companyName', 'address_1', 'country', 'state', 'city', 'zip'], 'required'],
['email', 'email'],
[['firstName', 'lastName', 'email', 'companyName', 'address_1', 'country', 'state', 'city', 'zip'], 'string', 'max' => 250],
];
}
public function attributeLabels() {
return [
'firstName' => 'First Name',
'lastName' => 'Last Name',
'email' => 'Email',
'companyName' => 'Company Name',
'address_1' => 'Address 1',
'country' => 'Country',
'state' => 'State',
'city' => 'City',
'zip' => 'Zip',
];
}
And I get validation errors after loading this data
"firstName": [
"First Name cannot be blank."
],
"lastName": [
"Last Name cannot be blank."
],
"email": [
"Email cannot be blank."
],
"companyName": [
"Company Name cannot be blank."
],
"address_1": [
"Address 1 cannot be blank."
],
"country": [
"Country cannot be blank."
],
"state": [
"State cannot be blank."
],
"city": [
"City cannot be blank."
],
"zip": [
"Zip cannot be blank."
]
So what's happening here is you're making a call to the load method of your model. This has 2 arguments, the first is your data and the second is a formName. When there is no formName argument declared, Yii2 will set it as equal to your model. So in this case it attempts to load data like this: $data['modelName']. So you could change your data array to follow the format of this:
$data = array(
'yourModel' => [
'yourData => 'yourValue'
]
)
But there's an easier way that doesn't require us to constantly remember how to construct our data arrays: set the 'formName' argument of the 'load' method to an empty string like so:
$model->load($data, '');
The reason this works is it allows the following code to run inside the 'load' method (where $scope is your formData argument):
if ($scope === '' && !empty($data)) {
$this->setAttributes($data);
return true;
}
This way we can continue writing our arrays in one less dimension, a small but nice way to keep our arrays ever-so-slightly tidier :).
Related
At my registration form, i have a bool input as newCompany with values
0=register to existed company with company code
1=create new company
Using required_if validation at different fields. And if it fails throws a validation message like "The Company Code field is required when Company is 0."
I wanna set that 0 value as Existing for 0 and New for 1. So i'm inserted them to my language file and changed :value attribute for default error message at lang/en/validation.php file.
'required_if' => 'The :attribute field is required when :other is :value.'
Here's my app/Requests/AuthRegisterRequest.php file:
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rules\Password;
use Illuminate\Validation\Rules\File;
use Illuminate\Http\Request;
class AuthRegisterRequest extends FormRequest {
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize() {
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array<string, mixed>
*/
public function rules(Request $request) {
return [
'name' => 'required|max:50|alpha',
'surname' => 'required|max:50|alpha',
'email' => 'required|email|unique:users,email',
'password' => [
'required',
Password::min(8)->numbers()->letters()->uncompromised(5)
],
'c_password' => 'required|same:password',
'newCompany' => 'required|boolean',
'companyCode' => 'nullable|required_if:newCompany,0|max:20|exists:user_companies,code',
'companyName' => 'nullable|required_if:newCompany,1|max:255',
'companyPhone' => 'nullable|required_if:newCompany,1|max:50|unique:user_companies,phone',
'activityTaxDocument' => [
'nullable',
'required_if:newCompany,1',
File::types(['jpg, jpeg, gif, png, doc, docx, pdf'])->max(5*1024) //5 MB
],
'privacyPolicies' => 'required|boolean'
];
}
public function attributes() {
return __('fieldname.AuthRegister');
}
public function messages() {
return [
'companyCode.required_if'=>__('validation.required_if', [
'value'=>__('fieldname.AuthRegister.newCompanyValues')['0']
]),
'companyName.required_if'=>__('validation.required_if', [
'value'=>__('fieldname.AuthRegister.newCompanyValues')['1']
]),
'companyPhone.required_if'=>__('validation.required_if', [
'value'=>__('fieldname.AuthRegister.newCompanyValues')['1']
]),
'activityTaxDocument.required_if'=>__('validation.required_if', [
'value'=>__('fieldname.AuthRegister.newCompanyValues')['1']
])
];
}
}
And lang/en/fieldname.php file
<?php
return [
'AuthRegister' => [
'name' => 'Name',
'surname' => 'Surname',
'email' => 'Email',
'password' => 'Password',
'c_password' => 'Confirm Password',
'newCompany' => 'Company',
'companyCode' => 'Company Code',
'companyName' => 'Company Name',
'companyPhone' => 'Company Phone',
'activityTaxDocument' => 'Activity/Tax Document',
'privacyPolicies' => 'Privacy Policy & Terms',
'newCompanyValues' => [
'1' => 'New',
'0' => 'Existing'
]
]
];
It's working but i wanna combine message for required_if validation to shorten the code according to newCompany field. But couldn't get input values at messages function.
Tried:
public function messages(Request $request) {
return [
'required_if'=>__('validation.required_if', [
'value'=>__('fieldname.AuthRegister.newCompanyValues')[$request->newCompany]
])
];
}
But it throws 500 with error below
{
"message": "Declaration of App\\Http\\Requests\\AuthRegisterRequest::messages(Illuminate\\Http\\Request $request) must be compatible with Illuminate\\Foundation\\Http\\FormRequest::messages()",
"exception": "Symfony\\Component\\ErrorHandler\\Error\\FatalError",
"file": "/var/www/html/app/Http/Requests/AuthRegisterRequest.php",
"line": 67,
"trace": []
}
I have a lot of forms like this. Some of them have much much more fields changing according a bool field. Is there a way to get input values at messages function or capture it from somewhere else?
if not, is it worth to defining a new rule, or should i just define it for each field separately?
Thanks.
I think you can use sometimes method without message() method
public function rules(Request $request) {
return [
'name' => 'required|max:50|alpha',
'surname' => 'required|max:50|alpha',
'email' => 'required|email|unique:users,email',
'password' => [
'required',
Password::min(8)->numbers()->letters()->uncompromised(5)
],
'c_password' => 'required|same:password',
'newCompany' => 'required|boolean',
'companyCode' => 'nullable|sometimes|required_if:newCompany,0|max:20|exists:user_companies,code',
'companyName' => 'nullable|sometimes|required_if:newCompany,1|max:255',
'companyPhone' => 'nullable|sometimes|required_if:newCompany,1|max:50|unique:user_companies,phone',
'activityTaxDocument' => [
'nullable',
'sometimes',
'required_if:newCompany,1',
File::types(['jpg, jpeg, gif, png, doc, docx, pdf'])->max(5*1024) //5 MB
],
'privacyPolicies' => 'required|boolean'
];
}
I need to test an array to make sure it has all elements I am expecing. The twist here is that we are talking about multidimensional arrays. Here is an example:
$required_data = [
'firstname',
'lastname',
'shipping' => [
'address',
'city',
'contacts' => [
'phone',
'email'
]
]
];
$incoming_data = [
'firstname' => 'Mike',
'shipping' => [
'address' => '1st Avenue',
'contacts' => [
'phone',
'email' => 'test#example.com'
]
]
];
I simply need to detect the two missing elements (lastname and city). I don't care about values. I test them separately.
At the moment I'm playing with this function just to get true when all required elements are provided or false otherwise.
It works when $incoming_data doesn't have any value but as soon as I start adding values (eg. Mike, 1st Avenue etc.) it fails.
function validate($incoming_data, $required_data)
{
foreach ($required as $key => $value) {
if (!isset($data[$key])) {
return false;
}
if (is_array($data[$key]) && false === validate($data[$key], $value)) {
return false;
}
}
return true;
}
I can't understand where my function starts playing with values. All is see are comparisons based on keys. Whut?
Thanks.
you have to set empty data in your $required_data tab like so :
$required_data = [
'firstname' => '',
'lastname' => '',
'shipping' => [
'address' => '',
'city' => '',
'contacts' => [
'phone',
'email'
]
]
];
I made the validation in the config / validation.php with references from the official documentation https://codeigniter4.github.io/userguide/libraries/validation.html like this:
class Validation
{
....
public $user = [
'name' => [
'rules' => 'required'
],
'email' => [
'rules' => 'valid_email|required',
'errors' => [
'valid_email' => 'E-mail is not valid',
'required' => 'E-mail is required'
]
]
];
}
and then I call it on my controller like this:
....
class User extends ResourceController
{
public function create()
{
$name = $this->request->getPost('name');
$email = $this->request->getPost('email');
$country = $this->request->getPost('country');
$province = $this->request->getPost('province');
$city = $this->request->getPost('city');
$day_of_birth = $this->request->getPost('day_of_birth');
$password = $this->request->getPost('password');
$phone_number = $this->request->getPost('phone_number');
$photo = $this->request->getPost('photo');
$data = [
'name' => $name,
'email' => $email,
'country' => $country,
'province' => $province,
'city' => $city,
'day_of_birth' => $day_of_birth,
'password' => $password,
'phone_number' => $phone_number,
'photo' => $photo
];
$validate = $this->validation->run($data,'user');
$errors = $this->validation->getErrors();
if($errors){
return $this->fail($errors);
}
return $this->respond($data);
}
}
when i tested it using postman, I get a return like this:
the validation works fine if I do it in the controller, but I want to declare the validation in validation.php, someone please help me, whatever I write in validation.php then i call using $this->validation->run($data,'name') always returns the same
You have not added the error message in the name required validation so maybe it's the problem so you must add an error message to the name.
Because validation in the message is important . Without any error messages, how can the user know what is the problem in the form.
Here is the customized function or sample of validation. change your function be like.
class Validation
{
public $user = [
'name' => [
'rules' => 'required',
'errors' => [
'required' => 'Name is required.'
]
],
'email' => [
'rules' => 'required|valid_email',
'errors' => [
'valid_email' => 'E-mail is not valid',
'required' => 'E-mail is required'
]
],
];
}
I am using laravel ver "laravel/framework": "5.8.*"
I want to save the data into database with post request and my post data is
I have searched on this many topics but I can't get any information on this specific topic. If anyone can, it will be very helpful to me.
I saw my previous codes they this type of code in laravel but they work fine why this is not saving and getting an error.
{
"userID": 11,
"fullname": "dharmendra shah",
"fatherName": "manohar shah",
"Mothername": "manorama devi",
"dobdate": "21",
"dobmonth": "August",
"dobYear": "1999",
"caste": "OBC",
"casteCertificateIs": "state",
"emailAddress": "dharmonly1999#gmail.com",
"gender": "Male",
"handiCappedStatus": "Not handicapped",
"nationality": "india",
"state": "Rajasthan",
"district": "bikaner",
"tahsil": null,
"village": "NA",
"maritalStatus": "UnMarried",
"spouseName": null,
"children": null
}
In laravel route my controller is :
public function store(Request $request)
{
$this->validate($request, [
'fullname' => 'required|max:25',
'fatherName' => 'required|max:25',
'Mothername' => 'required|max:25',
'dobdate' => 'required',
'dobmonth' => 'required',
'dobmonth' => 'required',
'dobYear' => 'required',
'caste' => 'required',
'casteCertificateIs'=>'required',
'emailAddress' => 'required|email',
'gender' => 'required',
'handiCappedStatus' => 'required',
'nationality' => 'required',
'state' => 'required',
'district' => 'required',
'block' => 'sometimes|max:20',
'tahsil' => 'sometimes|max:20',
'village' => 'sometimes|max:20',
'maritalStatus' => 'required',
'spouseName' => 'sometimes|max:20',
'children' => 'sometimes|max:5|integer'
]);
$userInformationSave = new BauserInformation([
'userID' => \Auth::user()->id,
'fullname' => $request->get('fullname'),
'fatherName' => $request->get('fatherName'),
'Mothername' => $request->get('Mothername'),
'dobdate' => $request->get('dobdate'),
'dobmonth' => $request->get('dobmonth'),
'dobYear' => $request->get('dobYear'),
'caste' => $request->get('caste'),
'casteCertificateIs' => $request->get('casteCertificateIs'),
'emailAddress' => $request->get('emailAddress'),
'gender' => $request->get('gender'),
'handiCappedStatus' => $request->get('handiCappedStatus'),
'nationality' => $request->get('nationality'),
'state' => $request->get('state'),
'district' => $request->get('district'),
'block' => $request->get('block'),
'tahsil' => $request->get('tahsil'),
'village' => $request->get('village'),
'maritalStatus' => $request->get('maritalStatus'),
'spouseName' => $request->get('spouseName'),
'children' => $request->get('children')
]);
$userInformationSave->save();
return redirect()->route('home')->with('message', 'Your information is saved now');
}
The model is
class BauserInformation extends Model
{
protected $table = ['userFinalInformation'];
protected $fillable = ['userID', 'fullname', 'fatherName', 'Mothername', 'dobdate', 'dobmonth', 'dobYear', 'caste', 'casteCertificateIs', 'emailAddress', 'gender', 'handiCappedStatus', 'nationality', 'state', 'district', 'Block', 'tahsil', 'village', 'maritalStatus', 'spouseName', 'children'];
}
the error argument i am getting is
ErrorException (E_NOTICE)
Array to string conversion
You are complicating things.
On top of your controller put: use Illuminate\Support\Facades\Validator;.
Delete $userInformationSave.
Validate inputs:
$validator = Validator::make($request->all(), [
'fullname' => ['required', 'max:25'],
... every other input like I have done
]);
if ($validator->fails()) {
return redirect('/bla bla bla/create')->withErrors($validator);
}
And save the model:
BauserInformation::create($request->all());
EDIT #1
In you model, you should declare table and A_I like this:
protected $table = 'userFinalInformation';
protected $primaryKey = 'userID';
I think this will do the job.
Here my code :
$rules = [
'name' => 'required|string|max:255',
'price' => 'required|numeric|min:0',
'unit' => 'required|in:piece,kg,m',
'price_type' =>'required|string',
'service' => [
'string',
'required',
Rule::in($services_ids->all()),
],
'facility' => [
'string',
'required',
Rule::in($facilities_ids->all()),
],
'conciergeries' => [
'array',
'required',
Rule::in($conciergeries_ids->all()),
],
];
$custom_messages = [
'required' => 'Vous devez sélectionner un(e) :attribute.'
];
$validated = request()->validate($rules, $custom_messages);
The problem is that my custom_messages only works with 'name', 'price', 'unit', 'price_type' but not with 'service', 'facility' and 'conciergeries'.
Questions :
How to apply my custom messages with 'service', 'facility' and 'conciergeries' too ?
How to create a custom message for specifically one field ?
Thank's !
You just need to specify for which field you want to change the message
Try it like:-
$custom_messages = [
'service.required' => 'Your custom message for required service',
'service.string' => 'Your custom message of service should be string',];
And same process for facility and conciergeries.