2011-09-12 71 views
16

有什麼辦法可以在JavaScript中使用正則表達式來驗證多種格式的日期,如:DD-MM-YYYY或DD.MM.YYYY或DD/MM/YYYY等?我需要所有這些在一個正則表達式中,我並不是很擅長。到目前爲止,我已經想出了這個:var dateReg = /^\d{2}-\d{2}-\d{4}$/; DD-MM-YYYY。我只需要驗證日期格式,而不是日期本身。使用正則表達式來驗證日期格式

+1

如果改變的唯一事情是分隔您可能感興趣的http://www.datejs.com/ –

+0

然後用'[\ - \/\。]'替換'-'(或者任何轉義)。 –

+0

這是您自己的自定義格式日期字符串。國際格式是:dd.mm.yyyy或mm/dd/yyyy或yyyy-mm-dd。 –

回答

20

你可以使用一個字符類([./-]),以使分隔符可以是任何定義的字符

var dateReg = /^\d{2}[./-]\d{2}[./-]\d{4}$/ 

或者更好的是,匹配第一個分隔符的字符類,然後捕獲它作爲ag roup ([./-]),並使用所捕獲的組\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 
+1

謝謝。除了斜線「/」沒有正確轉義外,它工作正常。 –

+0

我不認爲斜槓需要在角色類中逃脫,但如果你想逃脫它,沒有傷害。可能會讓文本編輯器中的語法更好地工作,但應該以任何方式工作。 –

+0

你能否爲第一個數字(月份)添加限制不超過'3'? – vsync

0

試試這個:

^\d\d[./-]\d\d[./-]\d\d\d\d$ 
8

建議的正則表達式將不會驗證日期,唯一的圖案。

所以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])); 
 
}

+0

驗證無效日期值將手動完成。如果我用你的解決方案輸入08-08-1991之類的東西,會因爲某種原因在javascript中出現「無效日期」。 –

+1

不在Fx中:我將該日期添加到http://jsfiddle.net/mplungjan/Mqh8D/ 你是哪一個瀏覽器? – mplungjan

+0

如果你使用parseInt,你必須使用基數10,因爲08和09是無效的八進制數字 – mplungjan

0

不要重新發明輪子。使用解析日期的預構建的解決方案,如http://www.datejs.com/

+3

我不想添加外部庫的原因是它不是必需的,它只會使網站加載速度變慢。但是,是的,這將是一個解決方案 –

14

格式,日,月和年:

var regex = /^(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.](19|20)\d\d$/;

+0

這部分驗證日期,但仍然允許像'30-02-2013'這樣的日期是無效的。需要更復雜的規則來說明不同的月份長度。 –

+2

從技術上說@BillyMoon,我們實際上是在驗證它的格式,而不是日期本身。你的朋友也允許像30-02-2013這樣的日期。 – nicoabie

+0

是的,我的目的是從有效日期中提取數字,並且不會嘗試進行驗證,這是您的做法。我想通過一些調整,你可以對日期進行合理的驗證,我希望看到你這樣做,但是在我看來,有一半驗證他們喜歡在懸崖邊上有一個弱籬笆,最好是沒有任何東西,以免有人倚靠在上面!更好的是擁有一個強大的。 –

0

@mplungjan,@愛德華 - 盧卡

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(); 
} 

新的日期( )使用當地時間,小時00:00:00將顯示我們有「夏令時」或「夏令時(夏令時)」事件的最後一天。

實施例:

new Date(2010,9,17) 
Sat Oct 16 2010 23:00:00 GMT-0300 (BRT) 

另一種替代方法是使用GETUTCDATE()。

4

可以使用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,DD-MM-YYYY日期格式。您可以簡單地擴展正則表達式來驗證任何日期格式。假設你想驗證YYYY/MM/DD,只需用「[ - | /]」替換「[ - ]」即可。此表達式可以驗證日期爲31,月至12,但閏年和月結束30天未驗證。

0

爲了確保它能正常工作,您需要驗證它。

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

}; 
0

如果您想驗證您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; 
    } 
0

請找到下面的代碼使執行日期驗證爲任何提供的格式或基於用戶區域設置來驗證開始/結束/日期。可能有一些更好的方法,但已經提出了這個問題。已經測試過的格式如:MM/dd/yyyy,dd/MM/yyyy,yyyy-MM-dd,yyyy.MM.dd,yyyy/MM/dd和dd-MM-yyyy。

注意提供的日期格式和日期字符串齊頭並進。

<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');" />