Javascript中MM / DD / YYYY的正则表达式 [英] Regular Expression for MM/DD/YYYY in Javascript

查看:130
本文介绍了Javascript中MM / DD / YYYY的正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚在javaScript中编写了这个正则表达式,但它似乎不起作用,这是我的函数:

I've just written this regular expression in javaScript however it doesn't seem to work, here's my function:

function isGoodDate(dt){
    var reGoodDate = new RegExp("/^((0?[1-9]|1[012])[- /.](0?[1-9]|[12][0-9]|3[01])[- /.](19|20)?[0-9]{2})*$/");
    return reGoodDate.test(dt);
}

这就是我在表单验证中调用它的方式

and this is how I call it in my form validation

if(!isGoodDate(userInput[1].value)){
           alert("date not in correct format of MM/dd/YYYY");
           return false;  
        }

现在我想要它返回MM / DD / YYYY但是如果我放了一个它的有效日期会提高警报吗?有没有想法?

now I want it to return MM/DD/YYYY however if I put a valid date in it raises the alert? Any ideas anyone?

推荐答案

试试这个:

function isGoodDate(dt){
    var reGoodDate = /^((0?[1-9]|1[012])[- /.](0?[1-9]|[12][0-9]|3[01])[- /.](19|20)?[0-9]{2})*$/;
    return reGoodDate.test(dt);
}

你要么声明一个正则表达式:

You either declare a regular expression with:

new RegExp("^((0?[1-9]|1[012])[- /.](0?[1-9]|[12][0-9]|3[01])[- /.](19|20)?[0-9]{2})*$")

或者:

/^((0?[1-9]|1[012])[- /.](0?[1-9]|[12][0-9]|3[01])[- /.](19|20)?[0-9]{2})*$/

注意 /

这篇关于Javascript中MM / DD / YYYY的正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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