日期在一个形式和验证 [英] Date in a form and validate

查看:89
本文介绍了日期在一个形式和验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



所以基本上一个文件是form.php和我必须以dd / mm / yy编写当前服务器的日期,用户可以编辑它。日期应以表单格式显示,例如在网页浏览器上应该出现日期:[23/9/2012]。



,而另一个文件即为进程.php我必须验证日期。



所以对于我的form.php这是我到目前为止写的:

 < html> 
< body>
<?php
if(isset($ _POST [date])){
$ date = date(d / m / y($ _ POST [date] ));
echo $ date;
}
?>
< form action =form.phpmethod =POST>
日期:< input type =textname =datevalue =Date/>

< / form>
< / body>
< / html>

日期在网络浏览器上显示的内容只是日期:[日期]不是日期。

解决方案

您可以使用正则表达式执行此操作:

 <?php 
if(isset($ _ POST ['date'])&&!空($ _ POST ['date '])){
$ date = trim($ _ POST ['date']);
}

$ regex ='/ ^((([1-2] [0-9])|([1-9]))/([2])/ 0-9] {4})|((([1-2] [0-9])|([1-9])|(3 [0-1]))/((1 [0-2] )|([3-9])|([1]))/ [0-9] {4})$ /';
if(preg_match($ regex,$ date)){
$ disp_date = $ date;

//更新db
$ error =''中的日期
}
else {
$ error ='无效的日期格式< br />';

//从db
$ disp_date = $ date_from_db获取最后一个日期
}
?>
<?= $ error?>
< form action =method =POST>
< input type =textvalue =<?= $ disp_date?> name =date/>
< input type =submitvalue =提交日期/>
< / form>

正则表达式如何工作:
DD / MM / YYYY:
DD必须为1-31,MM 1-12,YYYY为4位数字。



编辑:修复了二月的问题。


I am a little stuck here how to write a code for current date of the server and validate them.

So basically on one file is the form.php and i have to write the code for current date of the server in dd/mm/yy and this can be edited by the user. The date should appear in a form format for example on the web browser should appear date: [23/9/2012].

and on the other file which is the process.php I have to validate the date.

so for my form.php this is what i wrote so far:

<html>
<body>
 <?php
    if (isset ($_POST["date"])){
    $date = date("d/m/y"($_POST["date"]));
    echo $date;
    }
?>
<form action="form.php" method="POST">
Date: <input type="text" name="date" value="Date" />

</form>
</body>
</html>

what it appear on the web browser for date is only date:[date] just the word date but not the date. I've been stuck for an hour for this.

解决方案

You can do this with a regex:

    <?php
    if (isset($_POST['date']) && !empty($_POST['date'])) {
        $date = trim($_POST['date']);
    }

    $regex = '/^((([1-2][0-9])|([1-9]))/([2])/[0-9]{4})|((([1-2][0-9])|([1-9])|(3[0-1]))/((1[0-2])|([3-9])|([1]))/[0-9]{4})$/';
    if (preg_match($regex, $date)) {
        $disp_date = $date;

        //update the date in db
        $error = '';
    }
    else {
       $error = 'Invalid date format<br />';

       //get last date from db
       $disp_date = $date_from_db;
    }
    ?>
    <?=$error?>
    <form action="" method="POST">
        <input type="text" value="<?=$disp_date?>" name="date" />
        <input type="submit" value="Submit Date" />
    </form>

How the regex works: DD/MM/YYYY: DD must be 1-31, MM 1-12 and YYYY a 4 digit num.

Edit: Fixed the problem with February.

这篇关于日期在一个形式和验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆