如何阻止用户动态输入格式不正确的日期?

How can you stop a user from entering an incorrectly formatted date on the fly?

本文关键字:不正确 日期 格式 输入 何阻止 用户 动态      更新时间:2023-09-26

在理想情况下,如果用户在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事件(源),它将在每次击键后触发。