29
25

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

JavaScript フォーム入力文字制限(全角カナ、半角英数記号、半角数字)

Posted at

フォームで入力文字を固定する。
フォーカスが外れると、規定外の文字が消えて、規定文字だけ残ります。

カナのみ<input name="text1" type="text" id="text1"><br>
半角のみ<input name="text2" type="text" id="text2"><br>
数字のみ<input name="text3" type="text" id="text3"><br>
function checkChara(_type,_str){
	var tmp = _str.split("");
	for(var cnt=0;cnt<tmp.length;cnt++){
		switch(_type){
			case "katakana":
				if(tmp[cnt].match(/^[ァ-ヶー]*$/)==null){
					tmp[cnt] = "";
				}
			break;
			case "hankaku":
				if(tmp[cnt].match(/^[a-zA-Z0-9!-/:-@¥[-`{-~]+$/)==null){
					tmp[cnt] = "";
				}
			break;
			case "number":
				if(tmp[cnt].match(/^[0-9]+$/)==null){
					tmp[cnt] = "";
				}
			break;
		}
	}
	return tmp.join("");
}
$(document).ready(function(e) {
	$("#text1").change(function(e) {
		$(this).val(checkChara("katakana",$(this).val()));
	});
	$("#text2").change(function(e) {
		$(this).val(checkChara("hankaku",$(this).val()));
	});
	$("#text3").change(function(e) {
		$(this).val(checkChara("number",$(this).val()));
	});
});

おかしいところあったら指摘ください

29
25
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
29
25

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?