2011-11-09 6 views
1

完璧な世界では、指定された日付形式の次の期待された文字でない場合、ユーザーがasp.netページのテキストボックスに文字を入力するのを止めることができます。ユーザーは間違ってフォーマットされた日付を入力しないようにするにはどうすればいいですか?

フォーマット:dd-mm-yyyyユーザーが "22"と入力した後に " - "を入力すると、何も起こりませんでした。

javascriptを使用してこれが可能な方法はありますか?現在、正しいフォーマットの日付を確認する検証がありますが、これはボタンをクリックしたときにのみ発生します。

このシナリオでは、すべてのユーザーが正しい形式を認識し、間違いを犯した場合のみ、この方法をすばやく(即座に)修正する必要があります。

+1

これは「入力マスキング」と呼ばれます。その言葉を検索するか、ここを見てください:http://www.webresourcesdepot.com/javascript-input-masks/それはあなたの後ろのものかもしれません。 – nickf

答えて

2

をあなたはjqueryのを使用する準備ができているなら、あなたは、私が見つけた、おそらく安価な方法は、(OnKeyUpイベントを使用することです 日付マスクプラグイン http://plugins.jquery.com/project/DateMask

2

onInputイベントハンドラを追加し、パターンに対して検証を実行し、<input>の値を必要に応じて修正します。

0

を使用することができますsource)、すべてのキーストロークの後に起動します。

+1

['oninput']を使うには(http://whattheheadsaid.com/2010/09/effectively-detecting-user-input-in-javascript)をお勧めします(http://mathiasbynens.be/notes/oninput)代わりに。 –

1

そうかもしれません。日付形式を指定すると、ユーザーがJavaスクリプト内のテキストボックスのKeyUp/KeyPressイベントを介して入力したものと比較することができます。これは単純ではなく実装することができますjQueryのを使用して

各if文でそう
$(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 

     } 

    }); 

}); 

e.keyCode(または指定したブラウザで相当)の数値以上であるかどうかをチェックする必要があるすべては、「 - 」。私がむしろlastCharを使用している理由は、これがサポートするはずのブラウザを特定することを迷う必要がないからです。

とにかくlastCharがテキストボックスのテキストすでに入力されたテキストに1文字しか含まれていない限り、最後に入力された文字はマイナスです。この場合、テキストボックスの内容は空白の''に設定する必要があります。

ブリーフィター

関連する問題