Home  >  Article  >  Web Front-end  >  js verify date of birth regular expression

js verify date of birth regular expression

php中世界最好的语言
php中世界最好的语言Original
2018-05-03 15:41:3611952browse

This time I will bring you js verification of birth dateregular expression, what are the notesfor implementing js verification of birth date regular expression, the following is a practical case, let's come together take a look.

In brief

In form validation, regular expressions are often used to verify birth date. This article divides the date of birth into several parts and introduces step by step the complete process of implementing a date of birth verification. I believe that after understanding the content of this article, you will have a deeper understanding and stronger confidence in writing regular expressions.

We divide a birth date in the form of 2018-06-15 into three components: year, month and date, and write the corresponding regular rules respectively.

1 Year regular expression

First give the rule definition of year regular expression:

  • The year consists of 4 digits

  • Only accepts years starting with 19 and 20

According to the above rules, it is easy to write the regular expression of the year Formula:

var pattern = /^(19|20)\d{2}$/;
//输出 true
console.log(pattern.test("2008"));

where / / the two slashes and the characters between them are the definition of the regular expression literal; ^ means matching the beginning of the string , $ means matching the string End; ^(19|20) means matching a string starting with 19 or 20, a pair of parentheses is to combine several items into a unit; and \d{2} means matching any ASCII number twice, \d, etc. The value is [0-9], and {2} means matching the previous item 2 times.

The above regular expression can match the years from 1900 to 2099. If you want to limit the range of years, add the following rules:

  • The year starts in 1920

  • The year ends in 2018

According to the above rules, change the regular expression as follows:

var pattern = /^(19[2-9]\d{1})|(20((0[0-9])|(1[0-8])))$/;
//输出 false
console.log(pattern.test("1916"));
//输出 true
console.log(pattern.test("2008"));
//输出 false
console.log(pattern.test("2022"));

2 Month regular expression

First give the rule definition of the month regular expression:

  • The month can be 1-12

  • If the month is 1-9, you can add 0

Based on the above rules, the following regular rules and simple tests are given:

var pattern = /^((0?[1-9])|(1[0-2]))$/;
//输出 false
console.log(pattern.test("19"));
//输出 true
console.log(pattern.test("02"));
//输出 true
console.log(pattern.test("2"));
//输出 true
console.log(pattern.test("11"));

3 Date regular expression

First give the rule definition of date regular expression:

  • The date can be 1-31

  • If the date is 1-9, you can add 0 in front

Based on the above rules, the following regular rules and simple tests are given:

var pattern = /^((0?[1-9])|([1-2][0-9])|30|31)$/;
//输出 false
console.log(pattern.test("32"));
//输出 true
console.log(pattern.test("02"));
//输出 true
console.log(pattern.test("2"));

4 Combination verification

According to the above regular expression of year, month and date, the regular expression of date of birth is formed:

var pattern = /^((19[2-9]\d{1})|(20((0[0-9])|(1[0-8]))))\-((0?[1-9])|(1[0-2]))\-((0?[1-9])|([1-2][0-9])|30|31)$/;
//输出 true
console.log(pattern.test("1923-3-18"));
//输出 true
console.log(pattern.test("1923-4-31"));
//输出 true
console.log(pattern.test("1923-2-29"));
//输出 true
console.log(pattern.test("2016-2-29"));

It can be seen from the above test results that the above regular verification is not perfect, mainly due to the number of days in February, April, June, September and November.

5 Improvement

According to the question in step 4, add the limiting rules as follows:

  • There is no 31st day in April, June, September and November

  • February has 28 days in ordinary years

  • ##February has 29 days in leap years

Judgment of leap years in ordinary years:

A year that is evenly divisible by 4 is a leap year, and a year that is not evenly divisible by 4 is an ordinary year. But if it is a full hundred years, it is a leap year only if it is divisible by 400, otherwise it is an ordinary year.

Based on the new rules and instructions, the following regular functions and tests are given:

var checkBirth = function (val) {
  var pattern = /^((?:19[2-9]\d{1})|(?:20(?:(?:0[0-9])|(?:1[0-8]))))\-((?:0?[1-9])|(?:1[0-2]))\-((?:0?[1-9])|(?:[1-2][0-9])|30|31)$/;
  var result = val.match(pattern);
  if(result != null) {
    var iYear = parseInt(result[1]);
    var month = result[2];
    var date = result[3];
    if(/^((0?[469])|11)$/.test(month) && date == '31') {
      return false;
    } else if(parseInt(month) == 2){
      if((iYear % 4 ==0 && iYear % 100 != 0) || (iYear % 400 == 0)) {
        if(date == '29') {
          return true;
        }
      }
      if(parseInt(date) > 28) {
        return false;
      }
    }
    return true;
  }
  return false;
}
//输出 true
console.log(checkBirth("1923-3-18"));
//输出 false 4月份没有31日
console.log(checkBirth("1923-4-31"));
//输出 false 平年
console.log(checkBirth("1923-2-29"));
//输出 true 闰年
console.log(checkBirth("2016-2-29"));

上述正则表达式中利用了String的match()方法,该方法唯一参数是一个正则表达式,返回的是一个由匹配结果组成的数组。数组的第一个元素就是匹配的字符串,余下的元素则是正则表达式中用圆括号括起来的子表达式。而(:?...)这种形式多次出现,该种方式表示只是把项组合到一个单元,但不记忆与该组相匹配的字符。利用该种方法按照正则匹配的顺序分别取出了年月日项,以便后序比较。

根据上述分析与测试,我们不但实现了年月日的正则的一般判定,还实现了日期范围及2,4,6,9,11月等特殊月份天数的处理,测验结果达到了我们设定的目标。

根据上述讲解和分析,我们可以调整相应的限定规则,使其满足于特定场景下的项目需要。

延伸

根据 V2EX网友 xiangyuecn 的意见,上述checkBirth的逻辑代码太多,确实有点 low。现将上述代码更新如下:

var checkBirth = function (val) {
  var pattern = /^((19[2-9]\d{1})|(20((0[0-9])|(1[0-8]))))\-((0?[1-9])|(1[0-2]))\-((0?[1-9])|([1-2][0-9])|30|31)$/;
  if(pattern.test(val)) {
    var date = new Date(val);
    var month = val.substring(val.indexOf("-")+1,val.lastIndexOf("-"));
    return date && (date.getMonth()+1 == parseInt(month));
  }
  return false;
}

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

Vue.js中computed与methods使用与区别

js-cookie使用步骤详解

The above is the detailed content of js verify date of birth regular expression. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn