2017-04-25 41 views
1

jQuery的日期驗證,同時明確地輸入該輸入字段,而不是從日期選擇器jQuery的日期驗證,而在輸入欄下明確鍵入

選擇我只想最小日期爲今天。即我不想選擇未來的日期。

在日期選擇器中,我禁用了未來日期。但是,當我在字段中輸入日期時,它接受未來日期。

這裏是我的jQuery代碼

jQuery(document).ready(function() { 
    jQuery("#datepicker").datepicker({ maxDate: new Date(),dateFormat: 'MM/DD/YYYY' }); 
    jQuery('.fa-calendar').click(function() { 
    jQuery("#datepicker").focus(); 
    }); 
}); 
+1

爲什麼你不加'只讀= 「」'上輸入字段?因此,該用戶不會允許輸入日期..他只需要從datepicker中選擇 – Mufi

+0

您是否嘗試過使用'maxDate:0'? – Diego

+0

嘿,馬蒂結帳我的答案。那是你要的嗎? –

回答

1

我想可能你正在尋找這樣的東西。您可以通過輸入並輸入日期來驗證輸入日期。我還建議您只使用您的datepicker字段,以便用戶不能在@Mufi評論中說的無效輸入。

$(document).ready(function() { 
 
    $("#datepicker,#datepickerReadonly").datepicker({ 
 
    \t maxDate: new Date(), 
 
    \t dateFormat: 'dd/mm/yy', 
 
\t changeYear:true, 
 
\t changeMonth:true, 
 
    }); 
 
    
 
    $('.fa-calendar').click(function() { 
 
    $("#datepicker").focus(); 
 
    }); 
 
    
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<link href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet"/> 
 
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> 
 

 
<input type="text" id="datepicker"> 
 
<input type="button" id="" value="check" onclick="check_();"/><br> 
 
Read Only Example: <br><input type="text" readonly="readonly" id="datepickerReadonly"> 
 

 
<script> 
 
function check_(){ 
 
\t if(new Date($('#datepicker').val()) > new Date()){ 
 
\t \t alert("you are not allowed to select future date"); 
 
\t \t $('#datepicker').val(''); 
 
\t } 
 
} 
 
</script>

+0

我剛纔使用的功能... – Mathi

0

試試這個:

jQuery(document).ready(function() { 

     jQuery("#datepicker").datepicker({       
        dateFormat: 'MM/DD/YYYY', 
        maxDate: '+10Y', 
        minDate: '+0M', 
        changeMonth: true, 
        changeYear: true, 
        yearRange: "-0:+10", }); 

     jQuery('.fa-calendar').click(function() { 
     jQuery("#datepicker").focus(); 
     }); 
    }); 

這個例子可以讓你選擇最大10 years上年Today