(Yii)Datetime Validation fails - php

I'd like to validate form input that is datetime for article to be posted.
$model = new Post('update');
$model->attributes = $_POST['Post'];
if($model->validate()){
//But, validation fails...
}
This is the rule that I got to check if the input is datetime format or not.
I used this page(http://chris-backhouse.com/date-validation-in-yii/528) as reference.
But I get validation error for 'created'input.
public function rules()
{
return array(
//datetime validation
array('created', 'date', 'message' => '{attribute}: is not a datetime!', 'format' => 'YYYY-MM-DD HH:MM:SS'),
);
}
This is what I have in $models-attribute.
array(1) { ["created"]=> string(19) "2013-08-01 00:00:01" }
Could anyone knows how to make this work?
Thanks a lot in advance!!!

I would advice to use input formats in rule, since sometimes you want custom formats.
array('created', 'date', 'format'=>'yyyy-MM-dd hh:mm:ss', 'message'=>'{attribute} have wrong format'),
More about date formats here - http://www.yiiframework.com/doc/api/1.1/CDateTimeParser

On Yii 2.0.6 (and maybe Yii 1.x ?), the correct format is :
['creation_date', 'date', 'format'=>'yyyy-MM-dd HH:mm:ss']
It's not working if hours are not in CAPS.

Is this creation time of the post? Then you don't need to validate it at all and you should set it in beforeSave instead of sending it with POST
add this to your model:
public function beforeSave()
{
if($this->isNewRecord)
{
$this->created=new CDbExpression('NOW()');
}
return parent::beforeSave();
}

Related

Creating a custom validation error message in CodeIgniter4

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'
],
])){
...
}

How to format date fields before save in CakePHP 3?

I used this in AppController:
Time::setToStringFormat('dd/MM/YYYY');
The date field in my form is a input type "text" to allow my user writes something like 31/12/2015.
However when I try to save (MySQL date) I get some errors of Time Class because inside the table the value now is 00-00-0000
Alunos Controller code
Thanks !
My final solution was this on bootstrap:
date_default_timezone_set('America/Sao_Paulo');
setlocale(LC_ALL, 'pt_BR', 'pt_BR.utf-8', 'pt_BR.utf-8', 'portuguese');
Type::build('time')->useImmutable();
Type::build('date')->useImmutable()->useLocaleParser();
Type::build('datetime')->useImmutable()->useLocaleParser();
Type::build('timestamp')->useImmutable();
\Cake\I18n\Time::setToStringFormat('dd/MM/yyyy HH:mm:ss');
\Cake\I18n\Date::setToStringFormat('dd/MM/yyyy');
\Cake\I18n\FrozenTime::setToStringFormat('dd/MM/yyyy HH:mm:ss');
\Cake\I18n\FrozenDate::setToStringFormat('dd/MM/yyyy');
\Cake\I18n\I18n::locale('pt-BR'); //new !
Type::build('decimal')->useLocaleParser();
Type::build('float')->useLocaleParser();
maybe this could help someone.
public function beforeSave($event, $entity, $options) {
$entity->dateField = date('Y-m-d', strtotime($entity->dateField));
}
If you are just creating a new application with a fresh database, delete does dates having 0000-00-00 and change the column definition so it can accept nulls. Using 0000-00-00 for dates is usually a really bad thing as only errors and bugs can come out of it :)
Edit based on the comments below
It seems like the problem was getting a string field to be parsed from the local date format to what php can understand. For this task you just need to configure the DateTimeType class to parse the dates using a locale-aware format as described here http://book.cakephp.org/3.0/en/orm/database-basics.html#parsing-localized-datetime-data
// In bootstrap.php or AppController or your controller action:
use Cake\Database\Type;
...
Type::build('datetime')->useLocaleParser();
You can also set the locale parser to parse a specific format. For the code above to work, make sure you set your application to use a locale:
I18n::locale('fr-FR')
Easy solution insert date format in CakePHP 3.x in Models and custom out views:
Insert ['rule' => ['date','dmy']]
Example
public function validationDefault(Validator $validator)
{
...
$validator
->add('demo_example_date', 'valid', ['rule' => ['date','dmy']]) //Format valid '30-12-2015' or '30-12-05'
->requirePresence('demo_example_date', 'create')
->notEmpty('factura_fecha');
...
return $validator;
}
Out view, set AppController
...
use Cake\I18n\Time;
use Cake\Database\Type;
Time::$defaultLocale = 'es-ES';
Time::setToStringFormat('dd-MM-YYYY');
Type::build('datetime')->useLocaleParser();
class AppController extends Controller
{
...
}
works for me using Postgres.
File config/app.php
in variable Datasources['default'] add command 'SET datestyle TO ISO, DMY' to init
'Datasources' => [
'default' => [
'init' => ['SET datestyle TO ISO, DMY '],
],
in mysql
https://my.vertica.com/docs/7.1.x/HTML/Content/Authoring/SQLReferenceManual/Statements/SET/SETDATESTYLE.htm

Yii Framework 2.0 Rules Date Validator

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.

CodeIgniter Callback not working

I have checked all the questions of similar kind, and none of them are solving my problem, using CI 2.1.3, and HMVC from Wiredesignz.
I have in my form_validation.php config file the following rule:
array(
'field' => 'eta-renpal-1',
'label' => 'Renpal number (1)',
'rules' => 'required|callback_check_eta_group'
),
And in my ETA controller, I have this function (currently set to ALWAYS be invalid while testing):
public function check_eta_group($reference)
{
// Internal function for use by form validation system to check if the ETA group requirements are met.
$this->form_validation->set_message('check_eta_group', 'Other values in the group ' . $reference . ' are also required.');
return false;
}
For some reason, the "required" function works, but the callback does not. I have tried all other similar suggested solutions, and can't get them to work. Please help?
Edit: The callback does not appear to be called at all. I even did var_dump() in the callback to see if there is output on the screen - none...
Edit2:: See last comment by myself - using that work-around solves the problem, but it is not exactly what I wanted. So - if you have a better solution, please share :-)
See my last comment under the question
(Using a workaround explained here, stackoverflow.com/questions/3029717/…, it works. It is not the way I want it to work with callbacks, but as long as it works, it is probably alright. Thanks anyways.)
Thanks Frosty for your comments.
make sure your function checks are inside the same controller that you are actually running the custom checks in (i.e. it should be able to be called with self::check_eta_group)
I had trouble getting validation working with my checks inside of MY_Controller for instance.
But when i moved them into the extended controller it worked fine.
here are two checks and how I called them (all within the same controller)
// custom form validators for datepicker and timepicker
public function date_valid($date){
$month = (int) substr($date, 0, 2);
$day = (int) substr($date, 3, 2);
$year = (int) substr($date, 6, 4);
$this->form_validation->set_message('date_valid', 'The %s field is not a valid date');
return checkdate($month, $day, $year);
}
public function time_valid($time){
$this->form_validation->set_message('time_valid', 'The %s field is not a valid time');
if (preg_match("/^(1[0-2]|0?[1-9]):[0-5][0-9] (AM|PM)$/i", $time)) {
return TRUE;
} else {
return FALSE;
}
}
public function create_custom(){
// load models and libraries
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
// set form validation rules
$this->form_validation->set_rules('schedule_date', 'Schedule Date', 'required|callback_date_valid');
$this->form_validation->set_rules('schedule_time', 'Schedule Time', 'required|callback_time_valid');
....
if ($this->form_validation->run() == FALSE) { // failed validation
error_log("validation_errors: ".validation_errors());
}

symfony sfValidatorSchemaCompare and dateformat output problem

public function configure()
{
$this->widgetSchema['start_date'] = new sfWidgetFormInput();
$this->widgetSchema['end_date'] = new sfWidgetFormInput();
$this->validatorSchema->setPostValidator( new sfValidatorOr ( array(
new sfValidatorAnd( array
(new sfValidatorSchemaCompare('start_date', sfValidatorSchemaCompare::NOT_EQUAL, null),
new sfValidatorSchemaCompare('end_date', sfValidatorSchemaCompare::EQUAL, null)
)),
new sfValidatorSchemaCompare('start_date', sfValidatorSchemaCompare::LESS_THAN_EQUAL, 'end_date',
array('throw_global_error' => false), array('invalid' => 'The start date ("%left_field%") must be before the end date ("%right_field%")')))));
}
I've got following input dates which I want to check if the end date isn't before the start date:
Input: Start => 31/03/10 End=> 07/03/10
Output: The start date (2010-03-31) must be before the end date (2010-03-07)
Can you in some way change the date output? I need the error message to set the date format the same as the input.
Also my input fields are set with the wrong date format when the error appears.
Tried several things, but no luck at this moment. Didn't find a solution or information on symfony it self.
I'm using symfony version 1.2.11
I found a the solution together with a colleague.
After some tryouts, we found the solution to my initial problem. Instead of using that post validator, we wrote are own validator.
class StartBeforeEndDateValidator extends sfValidatorBase {
public function configure($options = array(), $messages = array()) {
parent::configure($options, $messages);
$this->addMessage('Invalid_daterange', 'Start date (%start%) must be before End date (%end%)!');
}
public function doClean($values) {
sfContext::getInstance()->getConfiguration()->loadHelpers('Date');
$timestampStart = sfContext::getInstance()->getI18N()->getTimestampForCulture($values['start_date'], sfContext::getInstance()->getUser()->getCulture());
$timestampEnd = sfContext::getInstance()->getI18N()->getTimestampForCulture($values['end_date'], sfContext::getInstance()->getUser()->getCulture());
if(format_date($timestampStart) > format_date($timestampEnd)){
throw new sfValidatorError($this, 'Invalid_daterange', array('start' => $values['start_date'], 'end' => $values['end_date']));
}
}
}
Usage of the validator in the symfony form:
public function configure() {
$this->widgetSchema['start_date'] = new sfWidgetFormInput();
$this->widgetSchema['end_date'] = clone $this->widgetSchema['start_date'];
$this->validatorSchema['start_date'] = new DateValidator();
$this->validatorSchema['end_date'] = clone $this->validatorSchema['start_date'];
$this->validatorSchema->setPostValidator(new StartBeforeEndDateValidator());
}
This was the solution to have always the same date format when it's being validated and when the validation is trigger with an error, the format of the date is correctly returned in the same date format as it was set.
Now one other "problem" that we encountered was when the save happened, the date format wasn't right for mysql. So we override the save function in our symfony form and apply the right date format.
example:
public function save($con = null){
$var = new Object();
if($this->taintedValues['id']!= ""){
$var->setId($this->taintedValues['id']);
}
$var->setStartDate(DateUtils::getIsoDateForCulture($this->taintedValues['start_date']));
$var->setEndDate(DateUtils::getIsoDateForCulture($this->taintedValues['end_date']));
$var->setIcpm($this->taintedValues['icpm']);
$var->save($con);
}
So once the validation is valid, it will perform the save function and set the right date format before actually save it into the database.
Hope that this is helpful for other people who had this problem.

Categories