js verify date of birth regular expression
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
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中文网其它相关文章!
推荐阅读:
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

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 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

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 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 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

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

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data
