问题
Most validation plugins just show an error message. However, I would like (datepicker) to prevent entering incorrect values at all, automatically reverting to last correct value (not the intitial value on page load, but last correct one).
How is that possible?
回答1:
It might be me, but I tend to find this is horrific UI: if I make a typo in a date or any other field, the last thing I want is to need to retype it from scratch.
Ideally, the UI should not allow you to enter an incorrect date in the first place.
If it does allow you to do so, then I'd much rather see the field highlight itself by switching its background color to red (perhaps with a non-intrusive error message) so I can find the typo and fix it without needing to re-enter it.
回答2:
I just found the lastVal param which seems to be what your looking for. Try this (answer is in CoffeeScript but easy to translate to JavaScript):
$(".date1").datepicker.onClose = (dateText, inst) ->
if selectedDateIsValid(dateText, inst)
// Process new date
else
$(this).val(inst.lastVal)
window.alert("The selected day is invalid: ", dateText)
回答3:
Please see this answer to a question about datepicker for some background information. So, you can make datepicker responsible to transform text input into date object. You can save previous valid value before such transformation and revert to it in case of problems with new input, like this:
// save current value
var currentDate = $('#dateInput').datetimepicker().val();
// transform current text input into date
$('#dateInput').datetimepicker('setDate', $('#dateInput').val());
// ...
// revert value in case you catch a problem with new date
$('#dateInput').datepicker().val(currentDate);
$('#dateInput').val($('#dateInput').datepicker().val());
来源:https://stackoverflow.com/questions/6095473/datepicker-revert-to-last-value-on-incorrect-input