Table of Contents
In brief" >In brief
1 Year regular expression" >1 Year regular expression
2 Month regular expression" >2 Month regular expression
3 Date regular expression" >3 Date regular expression
4 Combination verification" >4 Combination verification
5 Improvement" >5 Improvement
Home Web Front-end JS Tutorial JS uses regular rules to determine date of birth

JS uses regular rules to determine date of birth

May 09, 2018 am 09:33 AM
javascript judgment

This time I will bring you JS's use of regular expressions to determine the date of birth. What are the precautions for using JS's regular expressions to determine the date of birth? The following is a practical case, let's 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"));
Copy after login

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"));
Copy after login

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"));
Copy after login

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"));
Copy after login

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"));
Copy after login

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"));
Copy after login
The above regular expression uses the match() method of String. The only parameter of this method is a regular expression. Formula, returns an array composed of matching results. The first element of the array is the matched string, and the remaining elements are subexpressions enclosed in parentheses in the regular expression. The form (:?...) appears many times. This method means that the items are only grouped into one unit, but the characters matching the group are not memorized. This method is used to extract the year, month and day items in the order of regular matching for subsequent comparison.

根据上述分析与测试,我们不但实现了年月日的正则的一般判定,还实现了日期范围及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;
}
Copy after login

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

推荐阅读:

Angular集成三方UI框架、控件使用详解

JS常见函数使用详解

The above is the detailed content of JS uses regular rules to determine date of birth. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

How to determine whether a date is the previous day in Go language? How to determine whether a date is the previous day in Go language? Mar 24, 2024 am 10:09 AM

Question: How to determine whether the date is the previous day in Go language? In daily development, we often encounter situations where we need to determine whether the date is the previous day. In the Go language, we can implement this function through time calculation. The following will be combined with specific code examples to demonstrate how to determine whether the date is the previous day in Go language. First, we need to import the time package in the Go language. The code is as follows: import("time") Then, we define a function IsYest

jQuery usage practice: several ways to determine whether a variable is empty jQuery usage practice: several ways to determine whether a variable is empty Feb 27, 2024 pm 04:12 PM

jQuery is a JavaScript library widely used in web development. It provides many simple and convenient methods to operate web page elements and handle events. In actual development, we often encounter situations where we need to determine whether a variable is empty. This article will introduce several common methods of using jQuery to determine whether a variable is empty, and attach specific code examples. Method 1: Use the if statement to determine varstr="";if(str){co

See all articles