Javascript - регулярное выражение для проверки формата даты
Есть ли способ иметь регулярное выражение в JavaScript, которое проверяет даты в нескольких форматах, например: ДД-ММ-ГГГГ или ДД.ММ.ГГГГ или ДД / ММ / ГГГГ и т. Д.? Мне нужно все это в одном регулярном выражении, и я не очень хорошо с этим. До сих пор я придумал это: var dateReg = /^\d{2}-\d{2}-\d{4}$/;
для ДД-ММ-ГГГГ. Мне нужно только проверить формат даты, а не саму дату.
11 ответов
Вы можете использовать класс символов ([./-]
), чтобы разделителями могли быть любые из определенных символов
var dateReg = /^\d{2}[./-]\d{2}[./-]\d{4}$/
Или, что еще лучше, сопоставьте класс персонажа с первым разделителем, а затем захватите его как группу ([./-])
и использовать ссылку на захваченную группу \1
сопоставить второй разделитель, который будет гарантировать, что оба разделителя одинаковы:
var dateReg = /^\d{2}([./-])\d{2}\1\d{4}$/
"22-03-1981".match(dateReg) // matches
"22.03-1981".match(dateReg) // does not match
"22.03.1981".match(dateReg) // matches
Формат, дни, месяцы и год:
var regex = /^(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.](19|20)\d\d$/;
Предлагаемое регулярное выражение не будет проверять дату, только шаблон.
Таким образом, 99.99.9999 пройдет регулярное выражение.
Позже вы указали, что вам нужно только проверить шаблон, но я все еще думаю, что более полезно создать объект даты
function isDate(str) {
var parms = str.split(/[\.\-\/]/);
var yyyy = parseInt(parms[2],10);
var mm = parseInt(parms[1],10);
var dd = parseInt(parms[0],10);
var date = new Date(yyyy,mm-1,dd,0,0,0,0);
return mm === (date.getMonth()+1) && dd === date.getDate() && yyyy === date.getFullYear();
}
var dates = [
"13-09-2011",
"13.09.2011",
"13/09/2011",
"08-08-1991",
"29/02/2011"
]
for (var i=0;i<dates.length;i++) {
console.log(dates[i]+':'+isDate(dates[i]));
}
Вы можете использовать регулярные множественные выражения с помощью оператора OR (|).
function validateDate(date){
var regex=new RegExp("([0-9]{4}[-](0[1-9]|1[0-2])[-]([0-2]{1}[0-9]{1}|3[0-1]{1})|([0-2]{1}[0-9]{1}|3[0-1]{1})[-](0[1-9]|1[0-2])[-][0-9]{4})");
var dateOk=regex.test(date);
if(dateOk){
alert("Ok");
}else{
alert("not Ok");
}
}
Выше функция может проверять форматы даты ГГГГ-ММ-ДД, ДД-ММ-ГГГГ. Вы можете просто расширить регулярное выражение для проверки любого формата даты. Предположим, вы хотите проверить YYYY / MM / DD, просто замените "[-]" на "[-|/]". Это выражение может проверять даты до 31, месяцы до 12. Но високосные годы и месяцы, заканчивающиеся на 30 дней, не проверяются.
Использовать скобки /^\d{2}[.-/]\d{2}[.-/]\d{4}$/
http://download.oracle.com/javase/tutorial/essential/regex/char_classes.html
Ниже приведен код, который позволяет выполнять проверку даты для любого из предоставленных форматов или на основе языкового стандарта пользователя для проверки дат начала / с и конца / до. Могли бы быть и лучшие подходы, но они придумали это. Протестировали его для форматов, таких как: MM / дд / гггг, дд / мм / гггг, гггг-мм-дд, гггг.ММ.дд, гггг / мм / дд и дд-мм-гггг.
Примечание предоставленный формат даты и строка даты идут рука об руку.
<script type="text/javascript">
function validate(format) {
if(isAfterCurrentDate(document.getElementById('start').value, format)) {
alert('Date is after the current date.');
} else {
alert('Date is not after the current date.');
}
if(isBeforeCurrentDate(document.getElementById('start').value, format)) {
alert('Date is before current date.');
} else {
alert('Date is not before current date.');
}
if(isCurrentDate(document.getElementById('start').value, format)) {
alert('Date is current date.');
} else {
alert('Date is not a current date.');
}
if (isBefore(document.getElementById('start').value, document.getElementById('end').value, format)) {
alert('Start/Effective Date cannot be greater than End/Expiration Date');
} else {
alert('Valid dates...');
}
if (isAfter(document.getElementById('start').value, document.getElementById('end').value, format)) {
alert('End/Expiration Date cannot be less than Start/Effective Date');
} else {
alert('Valid dates...');
}
if (isEquals(document.getElementById('start').value, document.getElementById('end').value, format)) {
alert('Dates are equals...');
} else {
alert('Dates are not equals...');
}
if (isDate(document.getElementById('start').value, format)) {
alert('Is valid date...');
} else {
alert('Is invalid date...');
}
}
/**
* This method gets the year index from the supplied format
*/
function getYearIndex(format) {
var tokens = splitDateFormat(format);
if (tokens[0] === 'YYYY'
|| tokens[0] === 'yyyy') {
return 0;
} else if (tokens[1]=== 'YYYY'
|| tokens[1] === 'yyyy') {
return 1;
} else if (tokens[2] === 'YYYY'
|| tokens[2] === 'yyyy') {
return 2;
}
// Returning the default value as -1
return -1;
}
/**
* This method returns the year string located at the supplied index
*/
function getYear(date, index) {
var tokens = splitDateFormat(date);
return tokens[index];
}
/**
* This method gets the month index from the supplied format
*/
function getMonthIndex(format) {
var tokens = splitDateFormat(format);
if (tokens[0] === 'MM'
|| tokens[0] === 'mm') {
return 0;
} else if (tokens[1] === 'MM'
|| tokens[1] === 'mm') {
return 1;
} else if (tokens[2] === 'MM'
|| tokens[2] === 'mm') {
return 2;
}
// Returning the default value as -1
return -1;
}
/**
* This method returns the month string located at the supplied index
*/
function getMonth(date, index) {
var tokens = splitDateFormat(date);
return tokens[index];
}
/**
* This method gets the date index from the supplied format
*/
function getDateIndex(format) {
var tokens = splitDateFormat(format);
if (tokens[0] === 'DD'
|| tokens[0] === 'dd') {
return 0;
} else if (tokens[1] === 'DD'
|| tokens[1] === 'dd') {
return 1;
} else if (tokens[2] === 'DD'
|| tokens[2] === 'dd') {
return 2;
}
// Returning the default value as -1
return -1;
}
/**
* This method returns the date string located at the supplied index
*/
function getDate(date, index) {
var tokens = splitDateFormat(date);
return tokens[index];
}
/**
* This method returns true if date1 is before date2 else return false
*/
function isBefore(date1, date2, format) {
// Validating if date1 date is greater than the date2 date
if (new Date(getYear(date1, getYearIndex(format)),
getMonth(date1, getMonthIndex(format)) - 1,
getDate(date1, getDateIndex(format))).getTime()
> new Date(getYear(date2, getYearIndex(format)),
getMonth(date2, getMonthIndex(format)) - 1,
getDate(date2, getDateIndex(format))).getTime()) {
return true;
}
return false;
}
/**
* This method returns true if date1 is after date2 else return false
*/
function isAfter(date1, date2, format) {
// Validating if date2 date is less than the date1 date
if (new Date(getYear(date2, getYearIndex(format)),
getMonth(date2, getMonthIndex(format)) - 1,
getDate(date2, getDateIndex(format))).getTime()
< new Date(getYear(date1, getYearIndex(format)),
getMonth(date1, getMonthIndex(format)) - 1,
getDate(date1, getDateIndex(format))).getTime()
) {
return true;
}
return false;
}
/**
* This method returns true if date1 is equals to date2 else return false
*/
function isEquals(date1, date2, format) {
// Validating if date1 date is equals to the date2 date
if (new Date(getYear(date1, getYearIndex(format)),
getMonth(date1, getMonthIndex(format)) - 1,
getDate(date1, getDateIndex(format))).getTime()
=== new Date(getYear(date2, getYearIndex(format)),
getMonth(date2, getMonthIndex(format)) - 1,
getDate(date2, getDateIndex(format))).getTime()) {
return true;
}
return false;
}
/**
* This method validates and returns true if the supplied date is
* equals to the current date.
*/
function isCurrentDate(date, format) {
// Validating if the supplied date is the current date
if (new Date(getYear(date, getYearIndex(format)),
getMonth(date, getMonthIndex(format)) - 1,
getDate(date, getDateIndex(format))).getTime()
=== new Date(new Date().getFullYear(),
new Date().getMonth(),
new Date().getDate()).getTime()) {
return true;
}
return false;
}
/**
* This method validates and returns true if the supplied date value
* is before the current date.
*/
function isBeforeCurrentDate(date, format) {
// Validating if the supplied date is before the current date
if (new Date(getYear(date, getYearIndex(format)),
getMonth(date, getMonthIndex(format)) - 1,
getDate(date, getDateIndex(format))).getTime()
< new Date(new Date().getFullYear(),
new Date().getMonth(),
new Date().getDate()).getTime()) {
return true;
}
return false;
}
/**
* This method validates and returns true if the supplied date value
* is after the current date.
*/
function isAfterCurrentDate(date, format) {
// Validating if the supplied date is before the current date
if (new Date(getYear(date, getYearIndex(format)),
getMonth(date, getMonthIndex(format)) - 1,
getDate(date, getDateIndex(format))).getTime()
> new Date(new Date().getFullYear(),
new Date().getMonth(),
new Date().getDate()).getTime()) {
return true;
}
return false;
}
/**
* This method splits the supplied date OR format based
* on non alpha numeric characters in the supplied string.
*/
function splitDateFormat(dateFormat) {
// Spliting the supplied string based on non characters
return dateFormat.split(/\W/);
}
/*
* This method validates if the supplied value is a valid date.
*/
function isDate(date, format) {
// Validating if the supplied date string is valid and not a NaN (Not a Number)
if (!isNaN(new Date(getYear(date, getYearIndex(format)),
getMonth(date, getMonthIndex(format)) - 1,
getDate(date, getDateIndex(format))))) {
return true;
}
return false;
}
Ниже приведен фрагмент HTML
<input type="text" name="start" id="start" size="10" value="05/31/2016" />
<br/>
<input type="text" name="end" id="end" size="10" value="04/28/2016" />
<br/>
<input type="button" value="Submit" onclick="javascript:validate('MM/dd/yyyy');" />
Если вы хотите проверить свои date(YYYY-MM-DD)
наряду со сравнением, он будет полностью использован для вас...
function validateDate()
{
var newDate = new Date();
var presentDate = newDate.getDate();
var presentMonth = newDate.getMonth();
var presentYear = newDate.getFullYear();
var dateOfBirthVal = document.forms[0].dateOfBirth.value;
if (dateOfBirthVal == null)
return false;
var validatePattern = /^(\d{4})(\/|-)(\d{1,2})(\/|-)(\d{1,2})$/;
dateValues = dateOfBirthVal.match(validatePattern);
if (dateValues == null)
{
alert("Date of birth should be null and it should in the format of yyyy-mm-dd")
return false;
}
var birthYear = dateValues[1];
birthMonth = dateValues[3];
birthDate= dateValues[5];
if ((birthMonth < 1) || (birthMonth > 12))
{
alert("Invalid date")
return false;
}
else if ((birthDate < 1) || (birthDate> 31))
{
alert("Invalid date")
return false;
}
else if ((birthMonth==4 || birthMonth==6 || birthMonth==9 || birthMonth==11) && birthDate ==31)
{
alert("Invalid date")
return false;
}
else if (birthMonth == 2){
var isleap = (birthYear % 4 == 0 && (birthYear % 100 != 0 || birthYear % 400 == 0));
if (birthDate> 29 || (birthDate ==29 && !isleap))
{
alert("Invalid date")
return false;
}
}
else if((birthYear>presentYear)||(birthYear+70<presentYear))
{
alert("Invalid date")
return false;
}
else if(birthYear==presentYear)
{
if(birthMonth>presentMonth+1)
{
alert("Invalid date")
return false;
}
else if(birthMonth==presentMonth+1)
{
if(birthDate>presentDate)
{
alert("Invalid date")
return false;
}
}
}
return true;
}
Не изобретай велосипед. Используйте готовое решение для разбора дат, например, http://www.datejs.com/
Чтобы убедиться, что он будет работать, вам нужно проверить его.
function mmIsDate(str) {
if (str == undefined) { return false; }
var parms = str.split(/[\.\-\/]/);
var yyyy = parseInt(parms[2], 10);
if (yyyy < 1900) { return false; }
var mm = parseInt(parms[1], 10);
if (mm < 1 || mm > 12) { return false; }
var dd = parseInt(parms[0], 10);
if (dd < 1 || dd > 31) { return false; }
var dateCheck = new Date(yyyy, mm - 1, dd);
return (dateCheck.getDate() === dd && (dateCheck.getMonth() === mm - 1) && dateCheck.getFullYear() === yyyy);
};
@mplungjan, @ eduard-luca
function isDate(str) {
var parms = str.split(/[\.\-\/]/);
var yyyy = parseInt(parms[2],10);
var mm = parseInt(parms[1],10);
var dd = parseInt(parms[0],10);
var date = new Date(yyyy,mm-1,dd,12,0,0,0);
return mm === (date.getMonth()+1) &&
dd === date.getDate() &&
yyyy === date.getFullYear();
}
new Date () использует местное время, час 00:00:00 будет показывать последний день, когда у нас есть события "Летнее время" или "Летнее время".
Пример:
new Date(2010,9,17)
Sat Oct 16 2010 23:00:00 GMT-0300 (BRT)
Другой альтернативой является использование getUTCDate().