I am using Yii Framework 2.0. I have a form with a text input field which is meant for a date. I have read the Yii Framework 2.0 about the Class yii\validators\Validator and known all the validator keys which can be used inside of the rules() method in a model class. When I use the date key as below, it does not validate anything. It means that I still can put some text in that input field and can post the form.
When I changed it into boolean or email, I could see that it validates very well when I put something wrong in the input field. How can I validate a date value inside of an input field with Yii Framework 2.0?
My rules() method:
public function rules()
{
return [
[['inputfield_date'], 'required'],
[['inputfield_date'], 'safe'],
[['inputfield_date'], 'date'],
];
}
My view page:
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'inputfield_date')->textInput(); ?>
<?php ActiveForm::end(); ?>
Boy the Yii docs suck. They don't even give an example. Working from O'Connor's answer, this worked for me since I was assigning the value in 2015-09-11 format.
// Rule
[['event_date'], 'date', 'format' => 'php:Y-m-d']
// Assignment
$agkn->event_date = date('Y-m-d');
The docs don't even specify where format or timestampAttribute came from, or how to use them. It doesn't even say what the heck from_date and to_date are. And most of all, no examples!
Working solution. My rules() method:
public function rules()
{
return [
[['inputfield_date'], 'required'],
[['inputfield_date'], 'safe'],
['inputfield_date', 'date', 'format' => 'yyyy-M-d H:m:s'],
];
}
My form in the view page:
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'inputfield_date')->textInput(); ?>
<?php ActiveForm::end(); ?>
My method in controller:
if ($model->load(Yii::$app->request->post()) && $model->validate()):
if($model->save()):
// some other code here.....
endif;
endif;
Note that the date format depends on how you define your date format input field. Note once again that this is not an AJAX validator. After clicking on the submit button, you will see the error message if you enter something else which is not a date.
You can validate for date like this from model rules
public function rules(){
return [
[['date_var'],'date', 'format'=>'d-m-yy'],
[['from_date', 'to_date'], 'default', 'value' => null],
[['from_date', 'to_date'], 'date'],
];
}
Not 100% sure how it is in Yii2, but going out from Yii1 that had to look like this...
array('org_datetime', 'date', 'format'=>'yyyy-M-d H:m:s'),
(source: http://www.yiiframework.com/wiki/56/#hh8)
...I'd say i'd have to look something like this in Yii2:
['shopping_date', 'date', 'format' => 'yyyy-M-d H:m:s'],
Firstly, date validation relies on $model->validate(), so does not work inline but is only triggered by clicking Save (i.e. it's typically applied in actionCreate/actionUpdate).
Secondly, it's applied after other rules like 'required', and only if they pass, so even when you click Save, if anything else fails validation, those errors will show, but the date error will not.
In summary, date validation can only be tested by ensuring that all other rules pass and then clicking Save.
Related
How can i create a custom error message for a custom validation. I'm using codeIgniter4
Okay guys so I'm a bit of a newbie with CI4 and I have created a custom validation file using the spark command ./spark make:validation and it works but the problem is I still don't know how to customize the error message too for instance when I try to validate the date 05-06-2022 the message is Validation.isWeekday, I want to let it say something meaningful like date is not a weekday.
This is how my validation looks like
namespace App\Validation;
class CustomDateValidation
{
public function isWeekday(string $date): bool
{
return date("N", strtotime($date)) < 6;
}
}
And my controller function looks a bit like this
if($this-validate(['date'=>'required|isWeekday'])){
...
}
You can pass a options array for each field you want validate instead of just the rules string:
if($this-validate([
'date'=> [
'rules' => 'required|isWeekday',
'errors' => [
'required' => 'The date field is required',
'isWeekday' => 'The date must be a weekday'
],
])){
...
}
Take a scenario,
There are 2 fields available in the form.
1) input type file for manual upload.
2) input type = text to enter youtube video url.
is it possible using laravel built-in validations so that validation will be fired if user has left both fields empty!
I have gone through https://laravel.com/docs/5.3/validation but could not find what I wanted.
In your controller, you could do something like this:
$validator = Validator::make($request->all(), [
'link_upload' => 'required|etc|...',
]);
$validator2 = Validator::make($request->all(), [
'file_upload' => 'required|etc|...',
]);
if ($validator->fails() && $validator2->fails()) {
// return with errors
}
Try required-without-all validation rule. As given in documentation:
The field under validation must be present only when the all of the other specified fields are not present.
Assuming your fields name are url and file, your rule would be like below:
$rules = [
'url' => 'required_without_all:file',
'file' => 'required_without_all:url'
];
required_without:foo,bar,...
The field under validation must be present and not empty only when any of the other specified fields are not present.
Try this,
In youre update method add this
$this->validate($request, [
'fileName'=>'required',
'urlName'=>'required'
]);
dont forget to set the fillable in your model
protected $fillable = ['fileName','urlName'];
Hope this helps
I was trying to use the Yii2 ActiveForm encodeErrorSummary property because I wanted to put line-breaks on Yii2 validation error messages:
Example code snippet in MODEL file
public function rules()
{
return [['username', 'required', 'message' => 'long message first line here<br> long message last line here']];
}
Example code snippet in VIEW file
$form = ActiveForm::begin(['id' => 'myform',
'encodeErrorSummary' => false
]);
...
echo $form->field($model, 'username');
...
ActiveForm::end();
Official Yii2 Documentation describes encodeErrorSummary property as:
Whether to perform encoding on the error summary.
but it seemed not suitable for that in my case... Maybe it's me misunderstanding something (...error summary)?
So... what is it intended for, then?
Thank you!
It seems like you need to configure the $fieldConfig property like this:
ActiveForm::begin([
'fieldConfig' => [
'errorOptions' => ['encode' => false],
],
]);
for your requirement. The errorSummary is the summary that you echo with
<?= $form->errorSummary($model) ?>
before or after the form. What you want is a behavior at the field level, while this is an option to disable the encoding at the summary level.
I've been making some basic CRUD pages for my cakePHP app using the HtmlHelper for the views. This is handy for building forms but for date inputs the helper by default generates 3 select boxes for the date which is quite cumbersome to use.
HTML5 introduces the input[type=date] and most browsers now incorporate some nice native interfaces to deal with it; e.g. Chrome produces a nice date-picker for date inputs.
I know it is possible to make the HtmlHelper just make the input a text box instead of the 3 dropdown by doing the following:
echo $this->Form->input('my_date', array('type' => 'text'));
But when I do
echo $this->Form->input('my_date', array('type' => 'date'));
it ignores the 2nd arguement and goes back to the 3 selects.
Is there a way to get the helper to make a date input?
It seem the HtmlHelper has not yet evolved to make use of the "date" input.
If you tell the helper to generate the date input as a text field, adding a jQuery one-liner can convert it to a date input.
So:
echo $this->Form->input('my_date', array('type' => 'text'));
to generate the field. Then:
$('#idOfMyDate').attr('type', 'date');
To change it to a date input.
If anyone has a better way I'd be keen to hear it.
The CakePHP FormHelper uses Widgets to render different input types. For "datetime" types, it uses the DateTimeWidget per default.
To get a regular input with the attribute type="date", you just have to tell CakePHP which widget to use.
In the View (usually App\AppView.php), you can configure the FormHelper:
<?php
namespace App\View;
use Cake\View\View;
class AppView extends View
{
public function initialize() {
$this->loadHelper('Form', [
'widgets' => [
'datetime' => ['Basic'],
],
]);
}
}
?>
The BasicWidget is the most basic widget which is used to render regular text inputs.
Then, in your view, you can just use 'type' => 'date' as expected:
echo $this->Form->input('my_date', array('type' => 'date'));
Or, since CakePHP already sets the type to "date" since the database column is a datetime field you can just leave it like this:
echo $this->Form->input('my_date');
The result is a regular text input with type="date".
For future readers: In the most recent version of CakePHP, you would use the method Form::control instead of Form::input. Everything else still applies.
Try this:
echo $this->Form->text('my_date',array('type' => 'date');
Like this it'll work as a charm
<div class="form-group">
<label for="Description"><?php echo __('Date'); ?></label>
<div class='input-group date' id='datetimepicker1'>
<?php echo $this->Form->input('scheduled_date', array('label'=> false, 'div' => false, 'class'=>'form-control', 'type' => 'text')); ?>
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</div>
Some explanation:
'div' => false: it's necessary to desable the div rendered by input() FormHelper function
'label' => false: it's necessary to desable the label rendered by input() FormHelper function
Take a look at cake PHP form helper doc for more details
I solved this problem with jquery
PHP
<?= $this->Form->control('birth_date', ['value' => $birth_date->i18nFormat('yyyy-MM-dd'), 'type' => 'text']); ?>
JS
$('#birth-date').attr('type', 'date');
It's obvious that Cake's FormHelper is messing up with <input type "date">. Therefore I solved this problem the following way (in CakePHP 2.x)
Copy FormHelper.php from lib\Cake\View\Helper\
Paste it to app\View\Helper. Now Cake will use your Form Helper instead of its own.
Open the new FormHelper.php, go to protected function _getInput($args) {, search for case 'date': and change it from:
case 'date':
$options += array('value' => $selected);
return $this->dateTime($fieldName, $dateFormat, null, $options);
to:
case 'date':
return $this->{$type}($fieldName, $options);
Cake will now stop transforming <input type="date"> into select boxes.
Keep in mind that with every future release of Cake 2.x you will have to transfer possible changes in Cake's Form Helper into your own Form Helper manually.
So the framework is CodeIgniter 2.0.2. I have a form that has groups of fields that correspond to rows in a database. The names of the fields are in the format:
opt[0][foo]
opt[0][bar]
opt[1][foo]
opt[1][bar]
etc...
The index (1,2,etc...) does not correspond to row IDs in the database, it is simply a way to split up the groups of fields. There may be gaps in the index as users are able to add and remove an arbitrary number of the field groups. All groups are identical, that is, they contain exactly the same set of fields with the same second level names.
I want to be able to use CodeIgniter's validation library to validate the form and (p)re-populate as necessary. I've found plenty of posts (in addition to the excellent CI user guide) on the pre-populating and I know how to get the working with the re-populating in general. However, this is the first time I've had to try it with the indexed field names as above. I've tried the below and it doesn't work:
array(
'field' => 'opt[][foo]',
'label' => 'Foo',
'rules' => 'required'
)
I'm guessing I was just hoping for too much and CodeIgniter doesn't support what I need it to do. Extending the existing form validation library is an option so if anyone has been in the same situation and can provide some tips that would be very welcome.
UPDATE:
Just a little extra info, I've also tried validating a specifically indexed field (see below) and that also didn't work... As I understand it multidimensional validation should work in the specific case:
array(
'field' => 'opt[0][foo]',
'label' => 'Foo',
'rules' => 'required'
)
The following controller code works for me on CI 2.0.2
public function test() {
$this->load->library('form_validation');
$this->load->helper('form');
$this->form_validation->set_rules('test[test1][test2]', 'Test', 'required|valid_email');
$this->form_validation->run();
echo validation_errors();
echo form_open($this->uri->uri_string());
echo form_input('test[test1][test2]', set_value('test[test1][test2]'));
echo form_submit();
echo form_close();
}
You can use this to loop through the opt variable and set validation rules for each input.
if(!empty($opt))
{
foreach($opt as $id => $value)
{
$this->form_validation->set_rules('opt[' . $id . '][foo]', 'Foo', 'required');
$this->form_validation->set_rules('opt[' . $id . '][bar]', 'Bar', 'required');
}
}
You should take a look at the callback functions for the validating class - this should help you accomplish what you need for validation.