Laravel Validation If checkbox ticked then Input text is required? - laravel

I have been reading Laravel validation documentation. I am not clear how to combine two rules.
For example:
<input type="checkbox" name="has_login" value="1">
<input type="text" name="pin" value="">
If has_login checkbox is ticked then Input text pin value is required.
If has_login is not ticked then Input text pin is not required.
Laravel Validation:
public function rules()
{
return [
'has_login' => 'accepted',
'pin' => 'required',
];
}

Use required_with or required_if
required_with:foo,bar
The field under validation must be present and not empty only if any of the other specified fields are present.
return [
'has_login' => 'sometimes',
'pin' => 'required_with:has_login,on',
];
--
required_if:anotherfield,value
The field under validation must be present and not empty if the anotherfield field is equal to any value.
return [
'has_login' => 'sometimes',
'pin' => 'required_if:has_login,on',
];
--
https://laravel.com/docs/5.2/validation
--
Also, if the checkbox has_login is not checked, it will not send as part of the form submission

Related

Laravel validator for input arrays

First and foremost:
I did read both entries # laravel and stackoverflow
I am trying to validate an array containing input[text]. They are defined currently as:
<input type='text' name='user[0][name]'/><div>#error('user[0][name]'){{ $message }}#enderror</div>
<input type='text' name='user[1][name]'/><div>#error('user[1][name]'){{ $message }}#enderror</div>
I tried the 3 variants below as well:
<input type='text' name='user[][name]'/>
<input type='text' name='name[]'/>
<input type='text' name='name[0]'/>
My ExampleController does this, in the store() method:
$validator = Validator::make($request->all(), [
'user.*.name' => 'required|string',
])->validate();
I've also tried using:
$validatedData = $request->validate([
"user.*.name" => "required|string",
]);//*/
The other option that I've tried to use to match was (for the other case):
'name.*' => 'required|string',
None of these manage to print an error message in the div that follows the input.
The only way for me to get to see the error, is if I do the validation in of the two below (for each case):
"user[0][name]" => "required|string",
"name[0]" => "required|string",
So... what is it that I'm doing wrong?
user[0][name] is the correct syntax for naming your form input elements.
To access the error message(s), however, use dot notation: user.0.name.
Here's a working playground.

October CMS - Range field type or custom in Create / Update form

I need to set an input range on a form to create and update. In the October CMS documentation, I found a list solution, but in the register there is no "range" field.
<input type="range" min="0" max="100" step="1">
I'm using the "Builder Plugin".The closest thing to the solution was the "macros" feature, but the documentation about the feature didn't help much. Has anyone found a solution for creating their own input types or range?
October CMS is very extendable platform. You can extend each and every aspect of it.
Same goes for builder plugin you can extend it as per your needs.
Please hold on this answer will be long but You will find it lot of useful.
Final Results
It will add control to control list so you can easily add it and reuse it for other fields as well.
Configurable - you don't need to edit any file/partial to change its values. its all inside builder plugin. your values [min, max, step] field-name etc.. all you can edit/update from builder plugin.
Its automatic. means labels and field-name all will work like other controls you don't need to specify anything else. all will be dynamic.
So lets start extending builder plugin :)
add this code to your plugin boot method plugin.php, it will basically add the control to builder plugin control list. [1st image]
public function boot() {
\Backend\Widgets\Form::extend(function($widget) {
$widget->addViewPath(\File::symbolizePath('~/plugins/hardiksatasiya/sotest/classes/CustomDesignTimeProvider/field_partials'));
});
\Event::listen('pages.builder.registerControls', function($controlLibrary) {
$properties = [
'min' => [
'title' => 'Min',
'type' => 'string',
'default' => '0',
'ignoreIfEmpty' => false,
'sortOrder' => 81
],
'max' => [
'title' => 'Max',
'type' => 'string',
'default' => '100',
'ignoreIfEmpty' => false,
'sortOrder' => 82
],
'step' => [
'title' => 'Step',
'type' => 'string',
'default' => '10',
'ignoreIfEmpty' => false,
'sortOrder' => 83,
]
];
$controlLibrary->registerControl(
'my_range',
'Range Field',
'Custom Range Field',
\RainLab\Builder\Classes\ControlLibrary::GROUP_STANDARD,
'icon-arrows-h',
$controlLibrary->getStandardProperties(['stretch'], $properties),
\HardikSatasiya\SoTest\Classes\CustomDesignTimeProvider::class
);
});
.... your extra code ...
now you need to create/add required dependent files plugins/hardiksatasiya/sotest/classes/CustomDesignTimeProvider.php , plugins/hardiksatasiya/sotest/classes/CustomDesignTimeProvider/partials/_control-my_range.htm and plugins/hardiksatasiya/sotest/classes/CustomDesignTimeProvider/field_partials/_field_my_range.htm'
plugins/hardiksatasiya/sotest/classes/CustomDesignTimeProvider.php
<?php namespace HardikSatasiya\SoTest\Classes;
use File;
use RainLab\Builder\Classes\ControlDesignTimeProviderBase;
class CustomDesignTimeProvider extends ControlDesignTimeProviderBase {
public function renderControlBody($type, $properties, $formBuilder)
{
return $this->makePartial('control-'.$type, [
'properties'=>$properties,
'formBuilder' => $formBuilder
]);
}
public function renderControlStaticBody($type, $properties, $controlConfiguration, $formBuilder)
{
$partialName = 'control-static-'.$type;
$partialPath = $this->getViewPath('_'.$partialName.'.htm');
if (!File::exists($partialPath)) {
return null;
}
return $this->makePartial($partialName, [
'properties'=>$properties,
'controlConfiguration' => $controlConfiguration,
'formBuilder' => $formBuilder
]);
}
public function controlHasLabels($type)
{
return true;
}
}
plugins/hardiksatasiya/sotest/classes/CustomDesignTimeProvider/partials/_control-my_range.htm
<div class="builder-blueprint-control-text">
<i class="icon-arrows-h"></i> Range Field
</div>
while above steps will add our custom control to the plugin builder list, next step will be adding form field partial. [3rd image]
plugins/hardiksatasiya/sotest/classes/CustomDesignTimeProvider/field_partials/_field_my_range.htm
<!-- Range -->
<?php if ($this->previewMode): ?>
<span class="form-control"><?= $field->value ? e($field->value) : ' ' ?></span>
<?php else: ?>
<div style="display: flex;">
<span style="width: 30px; margin-right: 20px;" id="<?= $field->getId() ?>_val">
<?= $field->value ?>
</span>
<span>
[<?= $field->getConfig('min') ?>]
</span>
<input
type="range"
name="<?= $field->getName() ?>"
id="<?= $field->getId() ?>"
value="<?= e($field->value) ?>"
min="<?= $field->getConfig('min') ?>"
max="<?= $field->getConfig('max') ?>"
step="<?= $field->getConfig('step') ?>"
oninput="(function(input) { document.getElementById('<?= $field->getId() ?>_val').innerText = input.value; })(this)"
<?= $field->getAttributes() ?>
/>
<span>
[<?= $field->getConfig('max') ?>]
</span>
</div>
<?php endif ?>
This html files are just html markup so can edit them and add css/style according to your need.
Once you did following steps you will able to see your custom range control in form builder's control list. now you can add it update it just like any other default control.
Its fully dynamic you can choose field-name, min, max, step and it will be applied.
Note: Just make sure you replace author-name and plugin-name according to your setup in provided code.
if you have any doubts please comment.
Well this was unique and after some research and testing I came up with a way to do this. I will remark that there isn't any reason that I have personally found to justify a range slider in a form. So I understand why OctoberCMS doesn't have one natively.
Inside the builder plugin you need to add the input field of the value you want to be stored and change the setting to be read only.
Inside the builder plugin you will want to add a partial. I called my partial something.htm for testing purposes. The whole path to the partial is: $/dle/test/models/products/something.htm Note the $ is just to evoke the starting point of the search.
Not inside the something.htm partial I have this: The label and input of the range. Natively the range element doesn't show the amount but with javascript and jquery we can connect this range to the price field.
<label for="priceRange">Price Range</label>
<input id="priceRange" type="range" min="0" max="10" step=".25" onchange="updateTextInput(this.value);">
Now you have to go to your create.htm and update.htm pages under controller. IE: author/plugin/controllers/controller/create.htm. Here I have entered the javascript / jquery to connect the range to the input field.
<script>
function updateTextInput(val) {
document.getElementById('Form-field-Products-price').value=val;
}
var value = $('#Form-field-Products-price').val();
$('#priceRange').val(value);
</script>

set rules for array input field in Yii

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".');
}
}

how to validated to enter numbers only and show alert message when special charter entered

I want to validate input filed which allow entering numbers only and if numeric, alphabet or copy paste not allowed and show the alert message.
<input id="amount" name="amount" type="text" placeholder="Amount" class="form-control"></div>
This my input field.
I search on google but not getting a proper answer.
From the client side you might want to create an input that already validates, to prevent unnecissary requests
<input type="text" name="amount" pattern="[0-9]*" title="Numbers only">
or
<input type="number" name="amount" title="Numbers only">
Next you want to validate the same on the server, to protect your request.
public function store(Request $request)
{
$validatedData = $request->validate([
'amount' => 'required|nummeric',
]);
// do something with amount
}
Do a server side validation as below
In your model
public static function rules()
{
return [
'amount' => ['required','numeric'],
];
}
In your controller write below code
$validator = Validator::make($request->all(), Your ModelName::rules());
if ($validator->fails()){
//display error msg
}

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