Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
380 views
in Technique[技术] by (71.8m points)

Javascript date regex DD/MM/YYYY

I know there are a lot of regex threads out there by I need a specific pattern I couldn't fin anywhere

This regex validates in a YYYY-MM-DD format

/^d{4}[/-](0?[1-9]|1[012])[/-](0?[1-9]|[12][0-9]|3[01])$/

I need the pattern to be DD/MM/YYYY (day first since it's in spanish and only "/", "-" should not be allowed)

I searched several regex libraries and I think this one should work... but since I'm not familiar with regex I'm not sure it validates like that

(0[1-9]|[12][0-9]|3[01])[ .-](0[1-9]|1[012])[ .-](19|20|)dd

I also don't know ho to escape the slashes, I try to "see" the logic in the string but it's like trying "see" the Matrix code for me. I'm placing the regex string in a options .js

[...]  },
"date": {
                    "regex": (0[1-9]|[12][0-9]|3[01])[ .-](0[1-9]|1[012])[ .-](19|20|)dd,
                    "alertText": "Alert text AAAA-MM-DD"
                },
"other type..."[...]

So, if the regex is ok, how would I escape it? if it's not, what's the correct regex and how do I escape it? :P

Thanks a lot


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You could take the regex that validates YYYY/MM/DD and flip it around to get what you need for DD/MM/YYYY:

/^(0?[1-9]|[12][0-9]|3[01])[/-](0?[1-9]|1[012])[/-]d{4}$/

BTW - this regex validates for either DD/MM/YYYY or DD-MM-YYYY

P.S. This will allow dates such as 31/02/4899


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.6k users

...