You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Javascript如何验证Dialogflow传入的指定格式出生日期

实现方案

核心逻辑是先用正则匹配两种指定格式,再校验匹配到的日期本身合法有效,避免出现02/30/2024这类格式符合但实际不存在的日期。

实现步骤

  • 定义两个正则分别匹配要求的两类日期格式:
    • 匹配mm/dd/yyyy格式:限制月份范围01-12,日期范围01-31,年份为4位数字
    • 匹配dd 月份全称,yyyy格式:限制日期范围01-31,月份为英文全称,年份为4位数字
  • 正则匹配通过后,再校验Date对象的合法性,排除无效日期
  • 只有以上校验全部通过,才进入后续转ISO格式的处理逻辑

修改后代码

// 提前定义月份全称列表,复用在正则和日期校验中
const FULL_MONTHS = ['January','February','March','April','May','June','July','August','September','October','November','December'];
// 两类格式的正则
const REGEX_MMDDYYYY = /^(0[1-9]|1[0-2])\/(0[1-9]|[12][0-9]|3[01])\/\d{4}$/;
const REGEX_DD_FULLMONTH_YYYY = new RegExp(`^(0[1-9]|[12][0-9]|3[01]) (${FULL_MONTHS.join('|')}),\\d{4}$`);

// 日期合法性校验函数
const isValidDate = (d) => {
  return d instanceof Date && !isNaN(d);
}

const formatdob = (df, globalParameter) => {   
    try {                        
        const inputDob = df._request.queryResult.queryText // 修正原代码重复声明dob变量的问题
        globalParameter["dob"] = inputDob;
        
        // 格式校验+合法性校验
        const isFormatValid = REGEX_MMDDYYYY.test(inputDob) || REGEX_DD_FULLMONTH_YYYY.test(inputDob);
        const parsedDate = new Date(inputDob);
        if(inputDob.length !== 0 && isFormatValid && isValidDate(parsedDate)){
            return new Date(
                Date.UTC(
                  parsedDate.getFullYear(),
                  parsedDate.getMonth(),
                  parsedDate.getDate(),
                  parsedDate.getHours(),
                  parsedDate.getMinutes(),
                  parsedDate.getSeconds()
                )                
              ).toISOString();                              
        }                                   

        console.log("else block: invalid dob format or value");
        return inputDob;
    }                  
    catch (err) {
        console.log(err)
        throw err;
    }   
};

module.exports = formatdob;

补充说明

如果需要支持大小写不敏感的月份输入,比如august小写也能匹配,可以在正则末尾加i修饰符,修改REGEX_DD_FULLMONTH_YYYY的定义为:

const REGEX_DD_FULLMONTH_YYYY = new RegExp(`^(0[1-9]|[12][0-9]|3[01]) (${FULL_MONTHS.join('|')}),\\d{4}$`, 'i');

内容的提问来源于stack exchange,提问作者lakshmi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 06:57:02