如何阻止用户动态输入格式不正确的日期?
How can you stop a user from entering an incorrectly formatted date on the fly?
在理想情况下,如果用户在asp.net页面的文本框中输入的字符不是指定日期格式下一个期望的字符,我将能够阻止用户输入该字符。
对于格式:dd-mm-yyyy,如果用户键入"22"后跟除"-"以外的任何内容,则不会发生任何变化。
是否有一种方法可以使用javascript,我目前有验证,检查正确格式的日期,但这只发生在按钮单击。
在这种情况下,所有用户都知道正确的格式,应该只有在犯错误时才会被发现,这种方法应该快速(立即)纠正。
如果你已经准备好使用jquery,那么你可以使用日期掩码插件http://plugins.jquery.com/project/DateMask
添加一个onInput
事件处理程序,在那里对模式执行验证,并根据需要纠正<input>
的值。
如果你正在使用jQuery,这:http://digitalbush.com/projects/masked-input-plugin/是一个下降掩蔽插件。如果你不使用jQuery,你应该开始:)
是的,这是可能发生的。给定日期格式,您可以比较用户通过java脚本中文本框的KeyUp/KeyPress事件输入的内容。
使用JQuery可以很简单地实现:
$(function(){
$('#mytextbox').bind('keypress', function(event){
//this assumes that the format is dd-mm-yyyy
//the text in the textbox
var text = $('#mytextbox').val();
//last character entered
var lastCharIndex = (text.length-1) < 0 ? 0 : (text.length -1);
var lastChar = text[lastCharIndex];
if( lastCharIndex == 0 ){ //corresponds to the first d in dd
} else if (lastCharIndex == 1 ) { //corresponds to the second d in dd
} else if (lastCharIndex == 2 ) { //corresponds to the first '-' in dd-mm-yyyy
} else if (lastCharIndex == 3 ) { //corresponds to the first m
} else if (lastCharIndex == 4 ) { //corresponds to the second m
} else if (lastCharIndex == 5 ) { //corresponds to the second '-'
} else if (lastCharIndex == 6 ) { //corresponds to the first y
} else if (lastCharIndex == 7 ) { //corresponds to the second y
} else if (lastCharIndex == 8 ) { //corresponds to the third y
} else if (lastCharIndex == 9 ) { //corresponds to the forth y
} else { //default error handling
}
});
});
因此,在每个if语句中,您必须检查的是e.keyCode
(或指定浏览器中的等效内容)是否为数字或'-'。我宁愿使用lastChar
的原因是,我不必弄清楚这应该支持什么浏览器……
无论如何,如果lastChar
不是,只要将文本框的文本设置为它已经拥有的文本减去最后输入的字符,当然除非输入的文本只有1个字符,在这种情况下,文本框的内容应该设置为空白''
。
Bleepzter
我发现一个可能便宜的方法是使用OnKeyUp
事件(源),它将在每次击键后触发。
- 从int值来看,Javascript日期不正确
- Safari浏览器中的格式化日期不正确
- 格式为nnnnnnnn的字符串在电子表格中显示为日期或不正确
- JavaScript:日期不正确
- x轴上的日期不正确
- asp.net 图表控件显示不正确的工具提示日期时间值
- 日期() 结果不正确
- Javascript Date 对象不正确的日期
- 时间戳中的日期不正确,例如DD_MM_YYYY_HH_MI_SS
- Flot工具提示中显示的日期不正确
- Angular UI网格日期格式不正确
- MongoDB日期时间值存储不正确
- 日期在Highcharts图中显示不正确,时间数据不规则
- Jquery日期选择器图标位置不正确
- 输入日期字段中显示的星期几不正确
- D3嵌套格式设置日期不正确
- 在x轴使用毫秒时接收到不正确的日期时间
- JS日期对象解析不正确
- Javascript日期格式显示不正确的时间
- ECMAScript 5.1规范不正确?日期构造函数日期/时间格式解析为UTC