簡體   English   中英

驗證輸入是YYYY-MM-DD HH:mm:ss格式?

[英]Validate input is in YYYY-MM-DD HH:mm:ss format?

我正在編寫一個PHP腳本,它接受用戶輸入的值,必須是這樣的。

2011-06-17 00:00:00
...
2011-06-17 23:59:59

如何驗證它確實是正確的輸入?

或者,在輸入上使用strtotime(),然后在date()中使用它以您所需的格式。 這具有驗證用戶提供正確日期而不僅僅是正確格式的優點。 也就是說,當有人在2月31日投入時,正則表達式檢查不會被捕獲。

$date = strtotime($input);
if ($date === false) {
    throw Exception('bad date');
}
$formatted = date('<whatever>', $date);

您正在尋找ISO 8601的驗證。

以下是驗證該格式的示例正則表達式:

^([\+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])(\3([12]\d|0[1-9]|3[01]))?|W([0-4]\d|5[0-2])(-?[1-7])?|(00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))([T\s]((([01]\d|2[0-3])((:?)[0-5]\d)?|24\:?00)([\.,]\d+(?!:))?)?(\17[0-5]\d([\.,]\d+)?)?([zZ]|([\+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)?$

http://www.pelagodesign.com/blog/2009/05/20/iso-8601-date-validation-that-doesnt-suck/

或者更好,

Zend框架日期驗證

例:

$validator = new Zend_Validate_Date(array('format' => 'yyyy-MM-dd HH:mm:ss'))
$validator->isValid('2011-06-17 00:00:00');
/(\d{4}[\-]((0[1-9]|1[0-2]))[\-]((0[1-9]|1[0-9]|2[0-9]|3[0-1]))(([t-tT-T]|\s)((0[0-9]|1[0-9]|2[0-3]))[\:]((0[0-9]|1[0-9]|2[0-9]|3[0-9]|4[0-9]|5[0-9]))[\:]((0[0-9]|1[0-9]|2[0-9]|3[0-9]|4[0-9]|5[0-9]))([.][a-zA-Z0-9]*)?)?)$/i;

它的嘗試

2013-06-28 2013-06-28T13:35:59 2013-06-28 13:35:59 2013-06-28T13:35:59.000 2013-06-28 13:35:59.000 2013-06-28T13:35 :59.000Z 2013-06-28 13:35:59.000Z

它沒有簡化,雖然它可以大大簡化..

使用DateTime :: createFromFormat並檢查返回值。

要完成日期/時間驗證,請使用DateTime :: createFromFormat()和strtotime(),例如

// Convert it to test if the datetime can be successfully used. Finer than regex.
$dateformat = DateTime::createFromFormat('Y-m-d H:i:s', '2014-09-27 20:00:05');
$datereal = strtotime($inputStart);

if( $dateformat === FALSE || $datereal === FALSE )
    echo "Invalid format/datetime".

如果您願意,如果日期格式錯誤或根本不可能,您可以將支票分開以發布單獨的消息。

使用正則表達式: http//php-regex.blogspot.com/http://networking.ringofsaturn.com/Web/regex.php是開始學習的好地方

或使用此解決方案:

$exploded = explode($INPUT_STRING, " ");
$date_explode = explode($exploded[0],"-");
$time_explode = explode($exploded[1],":");
if (empty($date_explode[0])||empty($date_explode[1])||empty($date_explode[2])||empty($time_explode[0])||empty($time_explode[1])||empty($time_explode[2])) {
die ("ERROR! Not correct input format!");
}
 $date = strtotime('2011-13-17 23:00:00');
 if($date){print("legal");}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM