在完美的世界中,如果不是指定日期格式中的下一個預期字符,我將能夠阻止用戶在asp.net頁面上的文本框中輸入字符。如何阻止用戶在飛行中輸入錯誤格式的日期?
對於格式:dd-mm-yyyy如果用戶輸入「22」,然後再輸入「 - 」,則什麼都不會發生。
有沒有一種方法,這是可能的使用JavaScript,我有驗證當前,檢查日期的正確格式,但這隻發生在按鈕單擊。
在這種情況下,所有用戶都會知道正確的格式,並且應該只在發生錯誤時才被發現,這種方法應該很快(立即)糾正。
在完美的世界中,如果不是指定日期格式中的下一個預期字符,我將能夠阻止用戶在asp.net頁面上的文本框中輸入字符。如何阻止用戶在飛行中輸入錯誤格式的日期?
對於格式:dd-mm-yyyy如果用戶輸入「22」,然後再輸入「 - 」,則什麼都不會發生。
有沒有一種方法,這是可能的使用JavaScript,我有驗證當前,檢查日期的正確格式,但這隻發生在按鈕單擊。
在這種情況下,所有用戶都會知道正確的格式,並且應該只在發生錯誤時才被發現,這種方法應該很快(立即)糾正。
如果你準備使用jquery那麼你可以使用 日期面具插件 我發現http://plugins.jquery.com/project/DateMask
添加一個onInput
事件處理程序,執行那裏的模式驗證,並根據需要糾正<input>
的值。
如果你使用的是jQuery,這個:http://digitalbush.com/projects/masked-input-plugin/是一個descent masking插件。如果你不使用jQuery,你應該開始:)
,可能爲廉價的方式就是使用OnKeyUp
事件( source),每次擊鍵後都會觸發。
它[推薦](http://whattheheadsaid.com/2010/09/effectively-detecting-user-input-in-javascript)使用['oninput'](http://mathiasbynens.be/notes/oninput)代替。 –
是的,它可能發生。給定日期格式,您可以比較用戶通過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
這被稱爲「輸入掩碼」。對該術語進行搜索,或者看看這裏:http://www.webresourcesdepot.com/javascript-input-masks/也許類似的東西就是你所追求的。 – nickf