2011-11-09 23 views
1

在完美的世界中,如果不是指定日期格式中的下一個預期字符,我將能夠阻止用戶在asp.net頁面上的文本框中輸入字符。如何阻止用戶在飛行中輸入錯誤格式的日期?

對於格式:dd-mm-yyyy如果用戶輸入「22」,然後再輸入「 - 」,則什麼都不會發生。

有沒有一種方法,這是可能的使用JavaScript,我有驗證當前,檢查日期的正確格式,但這隻發生在按鈕單擊。

在這種情況下,所有用戶都會知道正確的格式,並且應該只在發生錯誤時才被發現,這種方法應該很快(立即)糾正。

+1

這被稱爲「輸入掩碼」。對該術語進行搜索,或者看看這裏:http://www.webresourcesdepot.com/javascript-input-masks/也許類似的東西就是你所追求的。 – nickf

回答

2

添加一個onInput事件處理程序,執行那裏的模式驗證,並根據需要糾正<input>的值。

0

,可能爲廉價的方式就是使用OnKeyUp事件( source),每次擊鍵後都會觸發。

+1

它[推薦](http://whattheheadsaid.com/2010/09/effectively-detecting-user-input-in-javascript)使用['oninput'](http://mathiasbynens.be/notes/oninput)代替。 –

1

是的,它可能發生。給定日期格式,您可以比較用戶通過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