HTML 입력 태그가 숫자 값만 허용하도록하는 방법은 무엇입니까?
특정 <input>
필드는 숫자 만 값 으로 사용하도록해야합니다 . 입력이 양식의 일부가 아닙니다. 따라서 제출되지 않으므로 제출하는 동안 유효성 검사가 옵션이 아닙니다. 사용자가 숫자 이외의 다른 문자를 입력 할 수 없도록하고 싶습니다.
이것을 달성하는 깔끔한 방법이 있습니까?
HTML 5
HTML5 입력 유형 번호 를 사용 하여 숫자 항목 만 제한 할 수 있습니다.
<input type="number" name="someid" />
이것은 HTML5 불만 브라우저에서만 작동합니다. html 문서의 doctype이 다음과 같은지 확인하십시오.
<!DOCTYPE html>
구형 브라우저에서의 투명한 지원에 대해서는 https://github.com/jonstipe/number-polyfill 을 참조하십시오 .
자바 스크립트
업데이트 : 이것에 대한 새롭고 매우 간단한 해결책이 있습니다.
다양한 숫자 필터를 포함 하여 텍스트에 모든 종류의 입력 필터 를 사용할 수 있습니다
<input>
. 복사 + 붙여 넣기, 드래그 + 드롭, 키보드 단축키, 상황에 맞는 메뉴 작업, 입력 할 수없는 키 및 모든 키보드 레이아웃을 올바르게 처리합니다.
참조 이 대답을 하거나 스스로를 시도 JSFiddle에 .
일반적인 목적으로 아래와 같이 JS 유효성 검사를 수행 할 수 있습니다.
function isNumberKey(evt){
var charCode = (evt.which) ? evt.which : evt.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
}
<input name="someid" type="number" onkeypress="return isNumberKey(event)"/>
소수를 허용하려면 "if condition"을 다음과 같이 바꾸십시오.
if (charCode > 31 && (charCode != 46 &&(charCode < 48 || charCode > 57)))
JSFiddle 데모 : http://jsfiddle.net/viralpatel/nSjy7/
html5에서 패턴 속성을 사용할 수도 있습니다.
<input type="text" name="name" pattern="[0-9]" title="Title" />
doctype이 아닌 경우 html
javascript / jquery를 사용해야한다고 생각합니다.
입력 코드 자체와 함께이 코드를 시도하십시오
<input type="text" name="price" id="price_per_ticket" class="calculator-input" onkeypress="return event.charCode >= 48 && event.charCode <= 57"></div>
잘 작동합니다.
을 사용할 수 있습니다 <input type="number" />
. 입력 상자에 숫자 만 입력 할 수 있습니다.
예 : http://jsfiddle.net/SPqY3/
입력 type="number"
태그는 최신 브라우저에서만 지원됩니다.
파이어 폭스의 경우 자바 스크립트를 사용하여 입력의 유효성을 검사 할 수 있습니다.
2018-03-12 업데이트 : 이제 브라우저 지원이 훨씬 향상되어 다음에 의해 지원됩니다.
- 크롬 6 이상
- Firefox 29 이상
- 오페라 10.1+
- 사파리 5+
- 가장자리
- (Internet Explorer 10 이상)
<input type="text" name="myinput" id="myinput" onkeypress="return isNumber(event);" />
그리고 js에서 :
function isNumber(e){
e = e || window.event;
var charCode = e.which ? e.which : e.keyCode;
return /\d/.test(String.fromCharCode(charCode));
}
또는 복잡한 bu 유용한 방법으로 작성할 수 있습니다.
<input onkeypress="return /\d/.test(String.fromCharCode(((event||window.event).which||(event||window.event).which)));" type="text" name="myinput" id="myinput" />
참고 : 크로스 브라우저 및 정규식은 정규식입니다.
입력 값을 필요한 패턴으로 대체하기 위해 정규식을 사용했습니다.
var userName = document.querySelector('#numberField');
userName.addEventListener('input', restrictNumber);
function restrictNumber (e) {
var newValue = this.value.replace(new RegExp(/[^\d]/,'ig'), "");
this.value = newValue;
}
<input type="text" id="numberField">
빠르고 쉬운 코드
<input type="text" onkeypress="return (event.charCode !=8 && event.charCode ==0 || (event.charCode >= 48 && event.charCode <= 57))" />
숫자와 백 스페이스 만 사용할 수 있습니다.
소수 부분도 필요한 경우이 코드 조각을 사용하십시오.
<input type="text" onkeypress="return (event.charCode !=8 && event.charCode ==0 || ( event.charCode == 46 || (event.charCode >= 48 && event.charCode <= 57)))" />
<input
onkeyup="value=isNaN(parseFloat(value))?1000:value"
type="number"
value="1000"
>
onkeyup
키에서 손을 떼면 트리거됩니다.
isNaN(parseFloat(value))?
입력 값이 숫자가 아닌지 확인합니다.
숫자가 아닌 경우 값은 1000으로 설정됩니다 :
. 숫자이면 값이 값으로 설정됩니다.
참고 : 어떤 이유로 든 작동합니다.type="number"
더 나가기 위해 경계를 만들 수도 있습니다.
<input
onkeyup="value=isNaN(parseFloat(value))||value<0||value>9000?1000:value"
type="number"
value="1000"
>
즐겨!
나는 이것과 조금 싸웠다. 여기 저곳의 많은 솔루션이 복잡해 보였습니다. 이 솔루션은 HTML과 함께 jQuery / javascript를 사용합니다 .
<input type="number" min="1" class="validateNumber">
$(document).on('change', '.validateNumber', function() {
var abc = parseInt($(this).val());
if(isNaN(abc)) { abc = 1; }
$(this).val(abc);
});
필자의 경우 최소값 1로 소량을 추적했기 때문에 입력 태그에서 min = "1"이고 isNaN () 검사에서 abc = 1입니다. 양수 만있는 경우 해당 값을 0으로 변경하고 입력 태그에서 min = "1"을 제거하여 음수를 허용 할 수도 있습니다.
또한 이것은 여러 상자에서 작동하며 ID로 개별적으로 수행하는 데 약간의로드 시간을 절약 할 수 있습니다. 필요한 경우 "validateNumber"클래스를 추가하십시오.
설명
parseInt ()는 기본적으로 정수 값이 아닌 NaN을 반환한다는 점을 제외하고 필요한 것을 수행합니다. 간단한 if ()를 사용하면 NaN이 반환되는 모든 경우에 선호하는 "대체"값을 설정할 수 있습니다 :-). 또한 W3는 상태 여기 NaN이의 글로벌 버전은 몇 가지 추가 교정 (Number.isNaN을 () 그렇게하지 않음) 제공합니다 확인하기 전에 캐스트를 입력 한 것입니다. 서버 / 백엔드로 전송 된 모든 값은 여전히 유효합니다!
function AllowOnlyNumbers(e) {
e = (e) ? e : window.event;
var key = null;
var charsKeys = [
97, // a Ctrl + a Select All
65, // A Ctrl + A Select All
99, // c Ctrl + c Copy
67, // C Ctrl + C Copy
118, // v Ctrl + v paste
86, // V Ctrl + V paste
115, // s Ctrl + s save
83, // S Ctrl + S save
112, // p Ctrl + p print
80 // P Ctrl + P print
];
var specialKeys = [
8, // backspace
9, // tab
27, // escape
13, // enter
35, // Home & shiftKey + #
36, // End & shiftKey + $
37, // left arrow & shiftKey + %
39, //right arrow & '
46, // delete & .
45 //Ins & -
];
key = e.keyCode ? e.keyCode : e.which ? e.which : e.charCode;
//console.log("e.charCode: " + e.charCode + ", " + "e.which: " + e.which + ", " + "e.keyCode: " + e.keyCode);
//console.log(String.fromCharCode(key));
// check if pressed key is not number
if (key && key < 48 || key > 57) {
//Allow: Ctrl + char for action save, print, copy, ...etc
if ((e.ctrlKey && charsKeys.indexOf(key) != -1) ||
//Fix Issue: f1 : f12 Or Ctrl + f1 : f12, in Firefox browser
(navigator.userAgent.indexOf("Firefox") != -1 && ((e.ctrlKey && e.keyCode && e.keyCode > 0 && key >= 112 && key <= 123) || (e.keyCode && e.keyCode > 0 && key && key >= 112 && key <= 123)))) {
return true
}
// Allow: Special Keys
else if (specialKeys.indexOf(key) != -1) {
//Fix Issue: right arrow & Delete & ins in FireFox
if ((key == 39 || key == 45 || key == 46)) {
return (navigator.userAgent.indexOf("Firefox") != -1 && e.keyCode != undefined && e.keyCode > 0);
}
//DisAllow : "#" & "$" & "%"
//add e.altKey to prevent AltGr chars
else if ((e.shiftKey || e.altKey) && (key == 35 || key == 36 || key == 37)) {
return false;
}
else {
return true;
}
}
else {
return false;
}
}
else {
return true;
}
}
<h1>Integer Textbox</h1>
<input type="text" autocomplete="off" id="txtIdNum" onkeypress="return AllowOnlyNumbers(event);" />
HTML5를 사용할 수 <input type="number" />
있다면 할 수 있다면 그렇지 않으면 코드 숨김에서 제출하지 않는다고 말한 것처럼 자바 스크립트를 통해 수행해야합니다.
<input id="numbersOnly" onkeypress='validate()' />
function validate(){
var returnString;
var text = document.getElementByID('numbersOnly').value;
var regex = /[0-9]|\./;
var anArray = text.split('');
for(var i=0; i<anArray.length; i++){
if(!regex.test(anArray[i]))
{
anArray[i] = '';
}
}
for(var i=0; i<anArray.length; i++) {
returnString += anArray[i];
}
document.getElementByID('numbersOnly').value = returnString;
}
추신 : 코드를 테스트하지는 않았지만 오타를 확인하지 않으면 다소 정확해야합니다.
How about using <input type="number"...>
?
http://www.w3schools.com/tags/tag_input.asp
Also, here is a question that has some examples of using Javascript for validation.
Update: linked to better question (thanks alexblum).
if not integer set 0
<input type="text" id="min-value" />
$('#min-value').change(function ()
{
var checkvalue = $('#min-value').val();
if (checkvalue != parseInt(checkvalue))
$('#min-value').val(0);
});
The accepted answer:
function isNumberKey(evt){
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
}
It's good but not perfect. It works out for me, but i get a warning that the if-statement can be simplified.
Then it looks like this, which is way prettier:
function isNumberKey(evt){
var charCode = (evt.which) ? evt.which : event.keyCode;
return !(charCode > 31 && (charCode < 48 || charCode > 57));
}
Would comment the original post, but my reputation is too low to do so (just created this account).
You can use the <input>
tag with attribute type='number'.
For example you can use <input type='number' />
This input field allows only numerical values. You can also specify the minimum value and maximum value that should be accepted by this field.
Please see my project of the cross-browser filter of value of the text input element on your web page using JavaScript language: Input Key Filter . You can filter the value as an integer number, a float number, or write a custom filter, such as a phone number filter. See an example of code of input an integer number:
<!doctype html>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Input Key Filter Test</title>
<meta name="author" content="Andrej Hristoliubov anhr@mail.ru">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<!-- For compatibility of IE browser with audio element in the beep() function.
https://www.modern.ie/en-us/performance/how-to-use-x-ua-compatible -->
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<link rel="stylesheet" href="https://rawgit.com/anhr/InputKeyFilter/master/InputKeyFilter.css" type="text/css">
<script type="text/javascript" src="https://rawgit.com/anhr/InputKeyFilter/master/Common.js"></script>
<script type="text/javascript" src="https://rawgit.com/anhr/InputKeyFilter/master/InputKeyFilter.js"></script>
</head>
<body>
<h1>Integer field</h1>
<input id="Integer">
<script>
CreateIntFilter("Integer", function(event){//onChange event
inputKeyFilter.RemoveMyTooltip();
var elementNewInteger = document.getElementById("NewInteger");
var integer = parseInt(this.value);
if(inputKeyFilter.isNaN(integer, this)){
elementNewInteger.innerHTML = "";
return;
}
//elementNewInteger.innerText = integer;//Uncompatible with FireFox
elementNewInteger.innerHTML = integer;
}
//onblur event. Use this function if you want set focus to the input element again if input value is NaN. (empty or invalid)
, function(event){ inputKeyFilter.isNaN(parseInt(this.value), this); }
);
</script>
New integer: <span id="NewInteger"></span>
</body>
</html>
Also see my page "Integer field:" of the example of the input key filter
For general purpose, you can have JS validation as below:
It will work for Numeric keypad and normal number key's
function isNumberKey(evt){
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode < 31 || (charCode >= 48 && charCode <= 57 ) || (charCode >= 96 && charCode <= 105 ))
return true;
return false;
}
<input name="someid" type="number" onkeypress="return isNumberKey(event)"/>
Add inside your input tag: onkeyup="value=value.replace(/[^\d]/g,'')"
I updated some answers posted to add the following:
- Add the method as extension method
- Allow only one point to be entered
Specify how many numbers after the decimal point is allowed.
String.prototype.isDecimal = function isDecimal(evt,decimalPts) { debugger; var charCode = (evt.which) ? evt.which : event.keyCode if (charCode > 31 && (charCode != 46 && (charCode < 48 || charCode > 57))) return false; //Prevent more than one point if (charCode == 46 && this.includes(".")) return false; // Restrict the needed decimal digits if (this.includes(".")) { var number = []; number = this.split("."); if (number[1].length == decimalPts) return false; } return true; };
I use this for Zip Codes, quick and easy.
<input type="text" id="zip_code" name="zip_code" onkeypress="return event.charCode > 47 && event.charCode < 58;" pattern="[0-9]{5}" required></input>
When using this code you cant use "BackSpace Button" in Mozilla Firefox you can only use backspace in Chrome 47 && event.charCode < 58;" pattern="[0-9]{5}" required>
http://www.texotela.co.uk/code/jquery/numeric/ numeric input credits to Leo Vũ for mentioning this and of course TexoTela. with a test page.
It's better to add "+" to REGEX condition in order to accept multiple digits (not only one digit):
<input type="text" name="your_field" pattern="[0-9]+">
참고URL : https://stackoverflow.com/questions/13952686/how-to-make-html-input-tag-only-accept-numerical-values
'development' 카테고리의 다른 글
브라우저에서 클라이언트 시간대 가져 오기 (0) | 2020.07.10 |
---|---|
dll의 .NET Framework 버전 확인 (0) | 2020.07.10 |
개발 서버가없는 장치에서 서명되지 않은 APK를 빌드하고 설치 하시겠습니까? (0) | 2020.07.10 |
Sinon 스텁을 쉽게 정리 (0) | 2020.07.10 |
bash를 사용하면 표준 오류를 다른 프로세스에 어떻게 파이프 할 수 있습니까? (0) | 2020.07.10 |