php Codeigniter - 日期格式 - 表单验证

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14359158/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 07:08:01  来源:igfitidea点击:

Codeigniter - Date format - Form Validation

phpcodeignitercodeigniter-form-helper

提问by KarSho

I'm using codeigniterwith PHP. I'm using following form,

我使用PHP。我正在使用以下表格,

<?php
    echo form_open('/register/create_new', $form_params);
?>

DOB: <input type="text" id="dob" name="reg[dob]">
     <input type="submit" value="Create Account" />
</form>

here, #dobis in dd-mm-yyyyformat.

在这里,#dobdd-mm-yyyy格式。

my validation code is,

我的验证码是,

array(
  'field' => 'reg[dob]',
  'label' => 'DOB',
  'rules' => 'required'
)

How can i set the rulesfor correct date validation?

如何设置rules正确的日期验证?

采纳答案by Abin Manathoor Devasia

you can do it with regex

你可以用 regex

$this->form_validation->set_rules('reg[dob]', 'Date of birth', 'regex_match[(0[1-9]|1[0-9]|2[0-9]|3(0|1))-(0[1-9]|1[0-2])-\d{4}]'); 

回答by Winks

You can take use of CodeIgniters callback functionsby creating a callback_date_valid() function that check if the date is valid.

您可以通过创建一个用于检查日期是否有效的 callback_date_valid() 函数来使用CodeIgniters 回调函数

And to check if it is valid, you could use PHP's checkdate function

并检查它是否有效,您可以使用PHP 的 checkdate 函数

array(
  'field' => 'reg[dob]',
  'label' => 'DOB',
  'rules' => 'required|date_valid'
)

function callback_date_valid($date){
    $day = (int) substr($date, 0, 2);
    $month = (int) substr($date, 3, 2);
    $year = (int) substr($date, 6, 4);
    return checkdate($month, $day, $year);
}

回答by Joha

I have a pretty clean solution for this. You can extend codeigniters form validation library.

我有一个非常干净的解决方案。您可以扩展 codeigniters 表单验证库。

Do this by putting a MY_Form_validation.php file in your application/libraries folder. This file should look like this:

通过将 MY_Form_validation.php 文件放在您的 application/libraries 文件夹中来做到这一点。该文件应如下所示:

class MY_Form_validation extends CI_Form_validation {

    public function __construct($rules = array()) {
        parent::__construct($rules);
    }


    public function valid_date($date) {
        $d = DateTime::createFromFormat('Y-m-d', $date);
        return $d && $d->format('Y-m-d') === $date;
    }
}

To add the error message, you go to your application/language/ folder and open the form_validation_lang.php file. Add an entry to the $lang array at the end of the file, like so:

要添加错误消息,请转到 application/language/ 文件夹并打开 form_validation_lang.php 文件。在文件末尾的 $lang 数组中添加一个条目,如下所示:

$lang['form_validation_valid_date'] = 'The field {field} is not a valid date';

Note that the key here must be the same as the function name (valid_date).

注意这里的key必须和函数名(valid_date)一样。

Then in your controller you use this as any other form validation function like for example 'required'

然后在您的控制器中,您将其用作任何其他表单验证功能,例如“必需”

$this->form_validation->set_rules('date','Date','trim|required|valid_date');

回答by tmsimont

I know this is old, but I just encountered the same issue. I like the answer Winks provided, but found that the code did not work. I modified it to this:

我知道这很旧,但我刚刚遇到了同样的问题。我喜欢 Winks 提供的答案,但发现代码不起作用。我将其修改为:

  public function your_form_handler($date)
  {
    // ....
    $this->form_validation->set_rules('date', 'Date', 'required|callback_date_valid');
    // ....
  }

  /**
   * Validate dd/mm/yyyy
   */
  public function date_valid($date)
  {
    $parts = explode("/", $date);
    if (count($parts) == 3) {      
      if (checkdate($parts[1], $parts[0], $parts[2]))
      {
        return TRUE;
      }
    }
    $this->form_validation->set_message('date_valid', 'The Date field must be mm/dd/yyyy');
    return false;
  }

回答by Muhammad

There is no builtin date validation in Codeigniter form_validationLibrary, but you can use its callback to call a function and validate the date using PHP's own capabilities.

Codeigniterform_validation库中没有内置日期验证,但您可以使用其回调来调用函数并使用 PHP 自己的功能验证日期。

With DateTime you can make the shortest date&time validator for all formats.

使用 DateTime,您可以为所有格式制作最短的日期和时间验证器。

function validateDate($date, $format = 'Y-m-d H:i:s')
{
    $d = DateTime::createFromFormat($format, $date);
    return $d && $d->format($format) == $date;
}

var_dump(validateDate('2012-02-28 12:12:12')); # true
var_dump(validateDate('2012-02-30 12:12:12')); # false
var_dump(validateDate('2012-02-28', 'Y-m-d')); # true
var_dump(validateDate('28/02/2012', 'd/m/Y')); # true
var_dump(validateDate('30/02/2012', 'd/m/Y')); # false
var_dump(validateDate('14:50', 'H:i')); # true
var_dump(validateDate('14:77', 'H:i')); # false
var_dump(validateDate(14, 'H')); # true
var_dump(validateDate('14', 'H')); # true

var_dump(validateDate('2012-02-28T12:12:12+02:00', 'Y-m-d\TH:i:sP')); # true
# or
var_dump(validateDate('2012-02-28T12:12:12+02:00', DateTime::ATOM)); # true

var_dump(validateDate('Tue, 28 Feb 2012 12:12:12 +0200', 'D, d M Y H:i:s O')); # true
# or
var_dump(validateDate('Tue, 28 Feb 2012 12:12:12 +0200', DateTime::RSS)); # true
var_dump(validateDate('Tue, 27 Feb 2012 12:12:12 +0200', DateTime::RSS)); # false

function was copied from this answeror php.net

函数是从此答案php.net复制的

回答by Smith

I've written this custom validator for ci3 - validates the d/m/Y H:i format - you can easily change that.

我已经为 ci3 编写了这个自定义验证器 - 验证 d/m/YH:i 格式 - 您可以轻松更改它。

$this->form_validation->set_rules("start_date", "Start Date", 'trim|callback__check_date_valid');


   public function _check_date_valid($date){

    $this->form_validation->set_message('_check_date_valid', "Please enter a valid date");
    $d = DateTime::createFromFormat('d/m/Y H:i', $date);

    if($d && $d->format('d/m/Y H:i') === $date || $date == ''){
        return true;
    }else{

        return false;
    }

}

回答by curiosity

Try this one out...i think it's more simple.

试试这个……我认为它更简单。

$this->form_validation->set_rules('date', 'Date', 'trim|required|callback_checkDateFormat');

function checkDateFormat($date) {
        $d = DateTime::createFromFormat('Y-m-d', $date);
        if(($d && $d->format('Y-m-d') === $date) === FALSE){
            $this->form_validation->set_message('checkDateFormat', ''.$date.' is not a valid date format.');
            return FALSE;
        }else{
            return TRUE;
        }
}

回答by Dayz

I like the answer tmsimont provided, but found that the code did not work if non numeric values enterd. Modified code is given below:

我喜欢 tmsimont 提供的答案,但发现如果输入非数字值,代码将不起作用。修改后的代码如下:

/**
    * Validate dd/mm/yyyy
    */
    public function date_valid(){
        $date=$this->input->post('dob');
        $parts = explode("/", $date);
        if (count($parts) == 3) {     
            if (is_numeric($parts[2])) {  
                if (is_numeric($parts[0])) {
                    if (is_numeric($parts[1])) {    
                        if (checkdate($parts[1], $parts[0], $parts[2])){
                            return TRUE;
                        }
                    }
                }
            }
        }

        $this->form_validation->set_message('date_valid', 'The Date field must be mm/dd/yyyy');
        return false;
    }

回答by Rahul Pawar

The actual Regex for Codeigniter Date validation :

Codeigniter 日期验证的实际正则表达式:

$this->form_validation->set_rules('reg[dob]','Date of birth',array('regex_match[/^((0[1-9]|[12][0-9]|3[01])[- \/.](0[1-9]|1[012])[- \/.](19|20)\d\d)$/]'));

I am using same expression for format dd-mm-yyyy and dd/mm/yyyy

我对格式 dd-mm-yyyy 和 dd/mm/yyyy 使用相同的表达式

No Warnings and errors :-)

没有警告和错误:-)

回答by iamyojimbo

Using Regex is probably the best way. I use this Regex that I found here for the format YYYY-MM-DD: http://www.regular-expressions.info/dates.html

使用 Regex 可能是最好的方法。我使用我在此处找到的正则表达式格式为 YYYY-MM-DD:http: //www.regular-expressions.info/dates.html

The actual Regex is:

实际的正则表达式是:

^(19|20)\d\d[- /.](0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])$

It has a nice explanation on how each section works so that you can modify it for different date formats.

它对每个部分的工作方式有很好的解释,以便您可以针对不同的日期格式对其进行修改。

Then you can use the code suggested by @Abin: (make sure you enclose it in some kind of delimiter)

然后您可以使用@Abin 建议的代码:(确保将其括在某种分隔符中)

$this->form_validation->set_rules('reg[dob]', 'Date of birth', 'regex_match[/^(19|20)\d\d[- /.](0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])$/]');