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!

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.


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

SublimeText3 English version
Recommended: Win version, supports code prompts!

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Chinese version
Chinese version, very easy to use

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function
