2017-06-19 238 views
0

我有一個接受日期的輸入文本字段。如果距離今天的日期不超過一個月,我需要驗證日期。 例如用戶在2017年7月19日之後無法進入。 如何驗證此字段。在JQuery中的輸入字段中輸入日期驗證

注意:它不是日期選擇器字段。

我嘗試下面的代碼

if(new Date(jQuery('#inputDate').val()) > (new Date().getDate()+31)) { 
       alert("you are not allowed to select after one month"); 
       jQuery('#inputDate').val('');} 
+0

@ Mathi你解決問題? – hasan

回答

0

您可以創建自定義AddDays方法,如果條件使用它像以下

Date.prototype.addDays = function(days) { 
 
    var yourDate = new Date(this.valueOf()); 
 
    yourDate.setDate(yourDate.getDate() + days); 
 
    return yourDate; 
 
} 
 

 
var yourDate= new Date(); 
 

 
$("#inputDate").on("change", function(e){ 
 
    // includes current day 
 
    if(new Date($(this).val()) >= yourDate.addDays(30)) 
 
    { 
 
     console.log("you are not allowed to select more than month"); 
 
     alert("you are not allowed to select more than month"); 
 
     $(this).val(""); 
 
    } 
 
    
 
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script> 
 
<input type="date" id="inputDate">

+0

您應該在輸入字段未通過時清除輸入字段,否則保留該值。你可以在你的功能清除它,而不是設置它。 –

+0

@MilanChheda謝謝你的信息,我已經更新了我的答案 – hasan

+0

不錯。你應該使用'$(this)'而不是用'jQuery('#inputDate')'再次創建一個新的''。 –