2011-09-12 73 views
16

Có cách nào để có một regex trong JavaScript xác thực ngày của nhiều định dạng, như: DD-MM-YYYY hoặc DD.MM.YYYY hoặc DD/MM/YYYY vv? Tôi cần tất cả những điều này trong một regex và tôi không thực sự tốt với nó. Cho đến nay tôi đã đưa ra điều này: var dateReg = /^\d{2}-\d{2}-\d{4}$/; cho DD-MM-YYYY. Tôi chỉ cần xác thực định dạng ngày chứ không phải ngày tháng.Javascript - Regex để xác thực định dạng ngày

+1

Bạn có thể quan tâm http://www.datejs.com/ –

+0

Nếu điều duy nhất mà thay đổi là dấu phân cách sau đó thay thế '-' bằng' [\ - \/\.] '(hoặc bất kỳ lần thoát nào). –

+0

Đó là chuỗi ngày định dạng tùy chỉnh của riêng bạn. Định dạng quốc tế là: dd.mm.yyyy hoặc mm/dd/yyyy hoặc yyyy-mm-dd. –

Trả lời

20

Bạn có thể sử dụng một lớp nhân vật ([./-]) để các seperators thể được bất kỳ của các nhân vật được xác định

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

Hoặc vẫn còn tốt hơn, phù hợp với lớp nhân vật cho người seperator đầu tiên, sau đó nắm bắt đó là ag roup ([./-]) và sử dụng một tham chiếu đến các nhóm bắt \1 để phù hợp với seperator thứ hai, mà sẽ đảm bảo rằng cả hai seperators đều giống nhau:

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

cảm ơn. khác với dấu gạch chéo "/" không được thoát đúng cách, nó hoạt động tốt. –

+0

Tôi không nghĩ rằng dấu gạch chéo cần phải được thoát ra bên trong một lớp nhân vật, nhưng không có hại trong việc thoát nó nếu bạn muốn. Có thể làm cho cú pháp chập chờn trong trình soạn thảo văn bản của bạn hoạt động tốt hơn, nhưng nên làm việc theo cách nào đó. –

+0

bạn có thể thêm giới hạn cho số đầu tiên (tháng) không được vượt quá '3' không? – vsync

0

Hãy thử điều này:

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

Các regex đề xuất sẽ không xác nhận ngày, chỉ có các mô hình.

Vì vậy, 99,99,9999 sẽ vượt qua regex.

sau Bạn đã xác định rằng bạn chỉ cần để xác nhận mô hình nhưng tôi vẫn nghĩ rằng đó là hữu ích hơn để tạo ra một đối tượng ngày

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

việc xác thực giá trị ngày không hợp lệ sẽ là được thực hiện bởi tôi bằng tay. nếu tôi nhập một cái gì đó như 08-08-1991 với giải pháp của bạn, sẽ làm cho tôi một "Ngày không hợp lệ" trong javascript vì một lý do nào đó. –

+1

Không phải trong Fx: Tôi đã thêm ngày đó vào http://jsfiddle.net/mplungjan/Mqh8D/ Trình duyệt nào là bạn? – mplungjan

+0

Nếu bạn sử dụng parseInt bạn PHẢI sử dụng radix 10 từ 08 và 09 là số bát phân không hợp lệ – mplungjan

0

Đừng tái phát minh ra bánh xe. Sử dụng một giải pháp được xây dựng trước cho những ngày phân tích, như http://www.datejs.com/

+3

lý do tôi không muốn thêm thư viện bên ngoài là nó không cần thiết, nó sẽ chỉ làm cho trang web tải chậm hơn. nhưng có, đó sẽ là một giải pháp –

14

Format, ngày, tháng và năm:

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

+0

Điều này một phần xác nhận ngày, nhưng vẫn cho phép các ngày như '30-02-2013' không hợp lệ. Cần có các quy tắc phức tạp hơn để tính toán các độ dài tháng khác nhau. –

+2

Nói về mặt kỹ thuật @BillyMoon, chúng tôi đang thực sự xác thực định dạng của nó chứ không phải chính ngày đó. Yours cho phép những ngày như 30-02-2013 quá bạn của tôi. – nicoabie

+0

Có, của tôi được thiết kế để trích xuất các số từ ngày hợp lệ và không cố gắng thực hiện xác thực mà bạn thực hiện.Tôi nghĩ rằng với một số điều chỉnh, bạn có thể có xác nhận hợp lý của ngày, mà tôi muốn nhìn thấy bạn làm, nhưng một nửa xác nhận họ có vẻ như tôi như có một hàng rào yếu trên một vách đá, tốt hơn để không có gì cả, vì sợ ai đó nghiêng trên đó! Vẫn còn tốt hơn để có một mạnh mẽ. –

0

@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 () sử dụng giờ địa phương, giờ 00:00:00 sẽ hiển thị ngày cuối cùng khi chúng tôi có các sự kiện "Thời gian mùa hè" hoặc "DST (Giờ tiết kiệm ánh sáng ban ngày)".

Ví dụ:

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

Một lựa chọn khác là sử dụng getUTCDate().

4

Bạn có thể sử dụng nhiều biểu thức chính quy với việc sử dụng toán tử 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"); 
    } 
} 

Hàm trên có thể xác thực định dạng ngày YYYY-MM-DD, DD-MM-YYYY. Bạn chỉ có thể mở rộng cụm từ thông dụng để xác thực bất kỳ định dạng ngày nào. Giả sử bạn muốn xác thực YYYY/MM/DD, chỉ cần thay thế "[-]" bằng "[- | /]". Biểu thức này có thể xác thực ngày tháng đến 31, tháng đến 12. Nhưng năm nhuận và tháng kết thúc với 30 ngày không được xác thực.

0

Để đảm bảo nó hoạt động, bạn cần phải xác thực.

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

Nếu bạn muốn xác date(YYYY-MM-DD) của bạn cùng với việc so sánh nó sẽ được sử dụng đầy đủ cho bạn ...

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

Hãy tìm trong đoạn code dưới đây cho phép để thực hiện việc xác nhận ngày cho bất kỳ định dạng được cung cấp nào hoặc dựa trên ngôn ngữ người dùng để xác thực ngày bắt đầu/từ và kết thúc/đến ngày. Có thể có một số cách tiếp cận tốt hơn nhưng đã đưa ra điều này. Đã thử nghiệm các định dạng như: MM/dd/yyyy, dd/MM/yyyy, yyyy-MM-dd, yyyy.MM.dd, yyyy/MM/dd và dd-MM-yyyy.

Lưu ý chuỗi ngày tháng và định dạng được cung cấp đi đôi với nhau.

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

Dưới đây là đoạn mã 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');" /> 
Các vấn đề liên quan