Jquery if条件,如果字符串格式不正确,将调用Alert

Jquery if Condition that will call an Alert if string not in proper format

本文关键字:不正确 调用 Alert 格式 字符串 if 条件 如果 Jquery      更新时间:2023-09-26

基本上,我正在尝试创建一个if条件,如果用户没有以适当的格式输入日期,即格式(2011-09-20),它将提醒用户这一事实。提前感谢!

使用正则表达式(然后检查它是否可以解析为实际日期)

var testValue = "2011-09-91";
if(!testValue.match(/^[0-9]{4}('-[0-9]{2}){2}$/) || isNaN(new Date(testValue)))
{
    alert("failure");
}

可以这样写:

if ('2011-09-20'.match(/[0-9]{4}-[0-9]{2}-[0-9]{2}/))
    alert('this is maybe a date in the correct format');
else
    alert('this is not the correct format');