set rules for array input field in Yii - validation

I have field where I can add multiple row on click "+" button. But I want to set required rules in Yii validator form.
['input_field_name', 'each', 'rule' => ['required']]
I have this input field
<input type="number" class="form-control reqInput input-unchanged" name="Domains[input_name][0][phone]">
<input type="number" class="form-control reqInput input-unchanged" name="Domains[input_name][1][phone]" value="">
<input type="number" class="form-control reqInput input-unchanged" name="Domains[input_name][2][phone]" value="">
I want required rules for each input field.

You can create your own validator for this.
in rules()
return [
// an inline validator defined as the model method validateCountry()
['country', 'validateCountry'],
];
add new function in your model:
public function validateCountry($attribute, $params, $validator)
{
//create you custom logic here, loop throughout an array and check the
//values, the code below is just example
if (!in_array($this->$attribute, ['USA', 'Indonesia'])) {
$this->addError($attribute, 'The country must be either "USA" or
"Indonesia".');
}
}

Related

Laravel - old() value of checkbox, in combination with the one loaded from the database

I have this checkbox code:
<div>
<input type="checkbox" id="allowfullscreen" name="allowfullscreen"
{{ $gallery->allowfullscreen == 1 ? 'checked' : '' }}>
</div>
This checks the checkbox based on the value taken from the database. Now, i would like to implement also the old data, in case of a failed submission.
For textboxes i do it like this:
<input id="galname"
type="text"
class="form-control #error('galname') is-invalid #enderror"
name="galname"
value="{{ old('galname') ?? $gallery->galname }}"
required autocomplete="galname" autofocus>
But it does not work this way for checkboxes since they need checked to be printed. The samples I found around here on SO only adress one of the two situations, but didnt find any that address both things for checkboxes.
How can this be done?
The second parameter you give the the old() function is used when the first value is null. So when you do old('name', "test") and no old value for 'name' is found, 'test' is used. So in your case, you could use:
<div>
<input type="checkbox" id="allowfullscreen" name="allowfullscreen"
{{ old('allowfullscreen', $gallery->allowfullscreen) == 1 ? 'checked' : '' }}>
</div>
This is ok even if you use all inputs in one blade template to use with create and update actions.
Will only work for POST request, obviously.
#if(old('published', (old('_token') ? false : ($slider->published ?? false)))) checked #endif
<div class="form-group">
<input class="form-check-input" type="checkbox" id="publish" name="published" value="1" #if(old('published', (old('_token') ? false : ($slider->published ?? false)))) checked #endif>
<label class="form-check-label" for="publish">{{ __('PubliƩ') }}</label>
#include('bo.modules.input-error', ['inputName'=>'published'])
</div>
Using this on request
/**
* Prepare the data for validation.
*
* #return void
*/
protected function prepareForValidation()
{
$this->merge([
'published' => $this->published ? true : false
]);
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'published' => 'required|boolean',
];
}

CodeIgniter form validation radio button not working

I have a form with 3 radio buttons. The IDs are unique in the form, and all three have the same name, namely "vehicle_type". The radio buttons are generated correctly when I do source view
<input type="radio" name="vehicle_type" id="type_vehicle" value="1">
<input type="radio" name="vehicle_type" id="type_trailer" value="2" checked>
<input type="radio" name="vehicle_type" id="type_plant" value="3">
I have no validation rule set for the radio group, yet my form complains that the field is required.
I can confirm that there is no validation rule by running:
echo $this->form_validation->has_rule('vehicle_type');
It indicates no validation. Using that call on another field, i.e., client_name, returns "boolean: 1"
Why would the field try to validate if there is no validation rule set?
EDIT
I am using Wiredesignz HMVC in my project, so the Form_validation class is extended.
if ($this->form_validation->run($this)) {
$test = do_file_upload($post_data);
} else {
var_dump(validation_errors());
// echos "The Vehicle type field is required"
}
This problem only occurs with radio buttons:
All other forms without radio buttons validate correctly using the same check: ($this->form_validation->run($this)
My form validation is set with this function:
public function set_form_validation_rules($data)
{
foreach ($data as $field) {
if (!empty($field['validation']['rules'])) {
if (!is_array($field['validation']['rules'])) {
$this->form_validation->set_rules($field['name'], $field['label'], $field['validation']['rules']);
} else {
foreach ($field['validation']['rules'] as $fv) {
$this->form_validation->set_rules($field['name'], $field['label'], $fv);
}
}
}
}
}
And the radio button is defined as:
$data['fields']['type_plant'] = [
'name' => 'vehicle_type',
'id' => 'type_plant',
'input_class' => 'input-group width-100',
'color' => 'red',
'value' => 3,
'validation' => '',
'checked' => ($posts['vehicle_type'] == 3)
];
The other two radio buttons in the group are the same, just have different values and IDs.
Use this,
$this->form_validation->set_rules('vehicle_type', 'Vehicle type', 'required');
Load library for form validation and other helpers in application/config/autoload.php
$autoload['libraries'] = array('form_validation');
$autoload['helper'] = array('form', 'url');
In your controller file :
$this->form_validation->set_rules('vehicle_type', 'Vehicle Type', 'required');
In your view file use below code for printing validation errors
<?php echo validation_errors(); ?>
The answers given above tells me how to use form validation. It is not what I requested. I am far beyond that - as they all worked, except for radio buttons. As it turns out, passing the validation array incorrectly to the function in the $data array. Once I passed the data correctly, the form validation also worked.
Hey Bro Try this maybe it can help
This method is very simple
In form
<div class="form-group">
<label for="vehicle_type" class="col-sm-3 control-label">vehicle</label>
<div class="col-sm-9">
<div class="col-md-3">
<label><input type="radio" name="vehicle_type" id="vehicle_type" value="1"> ONE </label>
</div>
<div class="col-md-3">
<label><input type="radio" name="vehicle_type" value="2"> TWO </label>
</div>
<div class="col-md-3">
<label><input type="radio" name="vehicle_type" value="3"> THREE </label>
</div>
<small class="info help-block"></small>
</div>
</div>
Set Your Controller
public function add_save(){
if ($this->input->post('vehicle_type') == "1"){
}else if($this->input->post('vehicle_type') == "2"){
}else if($this->input->post('vehicle_type') == "3"){
}else{
$this->form_validation->set_rules('vehicle_type', 'Vehicle', 'required');
}
if ($this->form_validation->run()) {
$save = [
'vehicle_type' => $this->input->post('vehicle_type')
];
$this->model_yourmoderl->add($save);
} else {
$this->data['errors'] = $this->form_validation->error_array();
}
$this->response($this->data);
}

Laravel 5.4 array validation as single field message

I have following situation, the problem is validation error occurring twice because there are two different fields. The requirement is, there should be only once "User is required."
HTML:
<input type="text" name="user[]" placeholder="First Name">
<input type="text" name="user[]" placeholder="Last Name">
Form Request:
public function rules()
{
return [
'user.*' => 'required|min:3',
];
}
public function messages()
{
return [
'user.*' => 'User is required',
];
}
Validation Output:
/**
* User is required field.
* User is required field.
*/
It was an urgent task so I have done it as follows.
HTML:
<input type="text" name="user_data[]" placeholder="First Name">
<input type="text" name="user_data[]" placeholder="Last Name">
Form Request:
public function rules()
{
$user = \Request::input('user_data');
$rules = [];
if ($user[0] === null || $user[1] === null) {
$rules['user'] = 'required';
}
return $rules;
}
public function messages()
{
return [
'user.required' => 'User is required'
];
}
Validation Output:
/**
* User is required
*/
Well, the request itself contains two fields named user[], and thus will validate the field twice.
What you can do is, make two text fields
firstName
lastName
Then before saving, make
$fullname=$request->firstName().' '.$request->lastName();
$user->user=$fullname;
$user->save();

Array field always stores the last value of the field into database

Help me working with array inputs on my project.
This is the form field:
<form action="" method="">
<input type="text" class="form-control" name="scores[]">
<input type="hidden" name="lesson_id[]" value="">
<input type="hidden" name="year_id" value="">
<input type="hidden" name="grade_id" value="">
<input type="hidden" name="clas_id" value="">
<input type="hidden" name="student_id" value="">
</form>
My Controller:
public function store(Request $request)
{
foreach ($request->scores as $score)
{
$scr = new Assestment;
$scr->year_id = $request->year_id;
$scr->grade_id = $request->grade_id;
$scr->clas_id = $request->clas_id;
$scr->student_id = $request->student_id;
foreach($request->lesson_id as $lesson)
{
$scr->lesson_id = $lesson;
}
$scr->score = $score;
$scr->save();
}
}
My Model:
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Assestment extends Model
{
protected $table = 'assestments';
protected $fillable = [
'year_id', 'grade_id', 'clas_id', 'student_id', 'lesson_id', 'score',
];
public function students()
{
return $this->belongsToMany('App\Models\Student');
}
}
I would like to make the value of field "scores[]" and "lesson_id[]" as array so that they store multiple data to database.
But when I submit the form, the "lesson_id[]" always store the last value of the form. For example, the field "lesson_id[]" contains multiple values like "1, 2, 3 , 4", but the value stored into database is always "4 (the last value of the field)".
What should I do?
Only the last value is stored because you stored the data after foreach loop.
If you want to store the socres[] and lesson_id[] as an array in the same table, you can use serialize()
$scr = new Assestment;
$scr->year_id = $request->year_id;
$scr->grade_id = $request->grade_id;
$scr->clas_id = $request->clas_id;
$scr->student_id = $request->student_id;
$scr->lesson_id = serialize($request->lesson_id);
$scr->score = serialize($request->$score);
$scr->save();
To retreive each value, use unserialize()

How to use a translation of the label to display an error, instead of the label's name, when registering a user?

When registering a new user, I use a RegisterFormRequest from Laravel.
How can I use the label name translations to display correctly the error message ?
Here is my html code,
<div>
<label for="password">
{{ Lang::get('form.password') }} *
</label>
<input name="password" type="password" required>
</div>
<div>
<label for="password_confirmation">
{{ Lang::get('form.password.confirm') }} *
</label>
<input name="password_confirmation" type="password" class="form-control" required>
</div>
Here is what is displayed. Note that the input field's "password" is used as is, but not any translations.
in the Http\Controllers\YourController.php
public function postRegister(RegisterFormRequest $request)
{
$validator = $this->registrar->validator($request->all());
$validator = $validator->setAttributeNames( [
'password' => 'My Password Name'
] );
will do the trick.
As #ali as implied, it might be better to put these values into your request class (it is where you can put the specific rules, so why not the specific label translation?).
in the Http\Controllers\YourController.php
public function postRegister(RegisterFormRequest $request)
{
$validator = $this->registrar->validator($request->all());
$validator = $validator->setAttributeNames( $request->messages() );
in the Http\Requests\RegisterFormRequest.php
public function messages()
{
return [
'password' => Lang::get('form.password'),
Laravel validation attributes "nice names"
And (as #mohamed-kawsara mentionned) in
resources/lang/de/validation.php
return [
...
"confirmed" => "The :attribute confirmation does not match.",
...
What you need is custom message in you request class.
Write this function in your request class.
public function messages()
{
return [
'password.required' => 'YOUR CUSTOM MESSAGE FOR PASSWORD REQUIREMENT'
];
}

Resources