简体   繁体   English

JavaScript出生日期难题

[英]Javascript date of birth conundrum

I need to validate a primitive date of birth field input in the format of: 我需要以以下格式验证原始出生日期字段输入:

'mmmyyyy' 'mmmyyyy'

Where the first 3 characters of the string must be an acceptable 3-letter abbreviation of the months of the year. 如果字符串的前3个字符必须是可接受的3个字母的缩写,则为年份的月份。 It can be lowercase, or uppercase, or a mix of any so long as it spells out jan or feb or mar etc etc etc. There is no built-in method that I am aware of that has a ready array of this specific format of a month to be able compare against user input. 它可以是小写或大写形式,也可以是任何形式的混合形式,只要它拼写出jan或feb或mar等,等等。我不知道有内置方法可以使用此特定格式的现成数组一个月就可以与用户输入进行比较。 I was thinking that I could maybe use the localeCompare() method in a for loop to test if the output is not 0 then append an error message accordingly. 我以为我可以在for循环中使用localeCompare()方法测试输出是否为0,然后相应地附加错误消息。

function dateTester() {
   var d = new Date(),
      i,
      mo = [],
      moIsValid;
   for (i = 0; i < 12; i += 1) {
      d.setMonth(i);
      mo.push(d.toLocaleString().split(' ')[1].substr(0, 3));
   }
   return new RegExp('^(' + mo.join('|') + ')', 'i');
}

var moIsValid = dateTester();
alert(moIsValid.test('fEb1992'));

If you don't want the user's current locale name for the days to be valid, then just switch toLocaleString() to toString() . 如果您不希望当日的用户当前语言环境名称有效,则只需将toLocaleString()切换为toString() But then, why don't you just do this instead: 但是,为什么不这样做呢?

var moIsValid = /^(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)/i;
alert(moIsValid.test('fEb1992'));

Unless you just really, really want to check a month with a "dynamic" test, you can do: 除非您真的希望通过“动态”测试检查一个月,否则您可以执行以下操作:

var months = 'jan,feb,mar,apr,may,jun,jul,aug,sep,oct,nov,dec';

months.indexOf('JaN1975'.toLowerCase().substring(0,3)

Checking with: 检查:

console.log(months.indexOf('JaN1975'.toLowerCase().substring(0,3)) != -1);
console.log(months.indexOf('oct1975'.toLowerCase().substring(0,3)) != -1);
console.log(months.indexOf('FEB1975'.toLowerCase().substring(0,3)) != -1);
console.log(months.indexOf('Ja1975'.toLowerCase().substring(0,3)) != -1);
console.log(months.indexOf('091975'.toLowerCase().substring(0,3)) != -1);

http://jsfiddle.net/ELMFu/ http://jsfiddle.net/ELMFu/

Gives: 给出:

true
true
true
false
false
new Date(str.replace(/(\D+)(\d+)/, "1 $1 $2"))

编辑:使用isNaN来测试日期是否解析失败。

I like this concise function for validating your input: 我喜欢这个简洁的功能来验证您的输入:

var months = "janfebmaraprmayjunjulaugsepoctnovdec";
function validate(dateString) {
    return dateString.length == 7 &&
           !(months.indexOf(dateString.substr(0,3).toLowerCase()) % 3) &&
           isFinite(dateString.substr(3));
}

http://jsfiddle.net/gilly3/NR3aG/ http://jsfiddle.net/gilly3/NR3aG/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM