отфильтровывание не числовых из текстового поля на клавиатуре [дубликат]

Если мы рассмотрим общие сценарии, в которых может быть выбрано это исключение, доступ к свойствам с объектом вверху.

Пример:

string postalcode=Customer.Address.PostalCode; 
//if customer or address is null , this will through exeption

здесь, если адрес имеет значение null, то вы получите NullReferenceException.

Итак, в качестве практики мы всегда должны использовать проверку нуля, прежде чем обращаться к свойствам в таких объектах (особенно в общих)

string postalcode=Customer?.Address?.PostalCode;
//if customer or address is null , this will return null, without through a exception
91
задан Amarghosh 11 May 2010 в 06:08
поделиться

28 ответов

<HTML>
  <HEAD>
    <SCRIPT language=Javascript>
       <!--
       function isNumberKey(evt)
       {
          var charCode = (evt.which) ? evt.which : evt.keyCode;
          if (charCode != 46 && charCode > 31 
            && (charCode < 48 || charCode > 57))
             return false;

          return true;
       }
       //-->
    </SCRIPT>
  </HEAD>
  <BODY>
    <INPUT id="txtChar" onkeypress="return isNumberKey(event)" 
           type="text" name="txtChar">
  </BODY>
</HTML>

Это действительно работает!

143
ответ дан MYGz 3 September 2018 в 14:58
поделиться

Я заметил, что для всех ответов, представленных здесь, все не работает, если мы выберем часть текста в текстовом поле и попытаемся перезаписать эту часть. Поэтому я изменил функцию, которая приведена ниже:

    <HTML>
  <HEAD>
    <SCRIPT language=Javascript>
       <!--
       function isNumberKey(evt)
       {
         var charCode = (evt.which) ? evt.which : event.keyCode;

if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57))
{
        return false;
}
 if (charCode == 46 && evt.srcElement.value.split('.').length>1 )
    {

        return false;

    } 

 if(evt.srcElement.selectionStart<evt.srcElement.selectionEnd)
    {
          return true;
    }

  if(evt.srcElement.value.split('.').length>1 && evt.srcElement.value.split('.')[1].length==2)
  {

     return false;
  }


    return true;
       }


       //-->
    </SCRIPT>
  </HEAD>
  <BODY>
    <INPUT id="txtChar" onkeypress="return isNumberKey(event)" 
           type="text" name="txtChar">
  </BODY>
</HTML>
0
ответ дан Abhishek Gahlout 3 September 2018 в 14:58
поделиться
<script type="text/javascript">

    function isNumberKey(evt) {
        var charCode = (evt.which) ? evt.which : event.keyCode;
        if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57))
            return false;

        return true;
    }

</script>

@Html.EditorFor(model => model.Orderids, new { id = "Orderids", Onkeypress=isNumberKey(event)})

Это отлично работает.

1
ответ дан Allan Pereira 3 September 2018 в 14:58
поделиться

Надеюсь, что это сработает для вас.

<input type="text" onkeypress="return chkNumeric(event)" />

<script>
    function chkNumeric(evt) {
        evt = (evt) ? evt : window.event;
        var charCode = (evt.which) ? evt.which : evt.keyCode;
        if (charCode > 31 && (charCode < 48 || charCode > 57)) {
            if (charCode == 46) { return true; }
            else { return false; }
        }
        return true;
    }
</script>
1
ответ дан Ankur Kumar 3 September 2018 в 14:58
поделиться

Начиная с ответа @rebisco:

function count_appearance(mainStr, searchFor) {
    return (mainStr.split(searchFor).length - 1);
}
function isNumberKey(evt)
{
    $return = true;
    var charCode = (evt.which) ? evt.which : event.keyCode;
    if (charCode != 46 && charCode > 31
            && (charCode < 48 || charCode > 57))
        $return = false;
    $val = $(evt.originalTarget).val();
    if (charCode == 46) {
        if (count_appearance($val, '.') > 0) {
            $return = false;
        }
        if ($val.length == 0) {
            $return = false;
        }
    }
    return $return;
}

Разрешает использовать только этот формат: 123123123 [.121213]

Демо здесь demo

0
ответ дан Babesh Florin 3 September 2018 в 14:58
поделиться

Следующий код работал для меня

Поле ввода с событием «onkeypress» следующим образом

<input type="text" onkeypress="return isNumberKey(this,event);" />

Функция «isNumberKey» выглядит следующим образом

function isNumberKey(txt, evt) {
  var charCode = (evt.which) ? evt.which : evt.keyCode;
  if (charCode == 46) {
    //Check if the text already contains the . character
    if (txt.value.indexOf('.') === -1) {
        return true;
    } else {
        return false;
    }
  } else {
    if (charCode > 31 && (charCode < 48 || charCode > 57))
        return false;
  }
  return true;
}

0
ответ дан Bharat Jain 3 September 2018 в 14:58
поделиться

Для десятичных чисел, а также позволяет отрицательные числа с 2-мя местами для десятичных знаков после точки ... Я изменил функцию на:

<input type="text" id="txtSample" onkeypress="return isNumberKey(event,this)"/>



function isNumberKey(evt, element){

        var charCode = (evt.which) ? evt.which : event.keyCode
        if (charCode > 31 && (charCode < 48 || charCode > 57) && !(charCode == 46 || charCode == 8 || charCode == 45))
            return false;
        else {
            var len = $(element).val().length;

            // Validation Point
            var index = $(element).val().indexOf('.');
            if ((index > 0 && charCode == 46) || len == 0 && charCode == 46) {
                return false;
            }
            if (index > 0) {
                var CharAfterdot = (len + 1) - index;
                if (CharAfterdot > 3) {
                    return false;
                }
            }

            // Validating Negative sign
            index = $(element).val().indexOf('-');
            if ((index > 0 && charCode == 45) || (len > 0 && charCode == 45)) {
                return false;
            }
        }
        return true;
    }
0
ответ дан Chris OnDaRocks 3 September 2018 в 14:58
поделиться

Принятое решение не является полным, так как вы можете ввести несколько «.», например 24 .... 22..22. с некоторыми небольшими модификациями он будет работать в соответствии с назначением:

<HTML><HEAD>
<script type="text/javascript">

 function isNumberKey(txt, evt) {

    var charCode = (evt.which) ? evt.which : evt.keyCode;
    if (charCode == 46) {
        //Check if the text already contains the . character
        if (txt.value.indexOf('.') === -1) {
            return true;
        } else {
            return false;
        }
    } else {
        if (charCode > 31
             && (charCode < 48 || charCode > 57))
            return false;
    }
    return true;
}

</SCRIPT></HEAD><BODY>
<input type="text" onkeypress="return isNumberKey(this, event);" /> </BODY></HTML>
16
ответ дан ecoologic 3 September 2018 в 14:58
поделиться

здесь скрипт, который поможет вам:

<script type="text/javascript">
// price text-box allow numeric and allow 2 decimal points only
function extractNumber(obj, decimalPlaces, allowNegative)
{
    var temp = obj.value;

    // avoid changing things if already formatted correctly
    var reg0Str = '[0-9]*';
    if (decimalPlaces > 0) {
        reg0Str += '\[\,\.]?[0-9]{0,' + decimalPlaces + '}';
    } else if (decimalPlaces < 0) {
        reg0Str += '\[\,\.]?[0-9]*';
    }
    reg0Str = allowNegative ? '^-?' + reg0Str : '^' + reg0Str;
    reg0Str = reg0Str + '$';
    var reg0 = new RegExp(reg0Str);
    if (reg0.test(temp)) return true;

    // first replace all non numbers
    var reg1Str = '[^0-9' + (decimalPlaces != 0 ? '.' : '') + (decimalPlaces != 0 ? ',' : '') + (allowNegative ? '-' : '') + ']';
    var reg1 = new RegExp(reg1Str, 'g');
    temp = temp.replace(reg1, '');

    if (allowNegative) {
        // replace extra negative
        var hasNegative = temp.length > 0 && temp.charAt(0) == '-';
        var reg2 = /-/g;
        temp = temp.replace(reg2, '');
        if (hasNegative) temp = '-' + temp;
    }

    if (decimalPlaces != 0) {
        var reg3 = /[\,\.]/g;
        var reg3Array = reg3.exec(temp);
        if (reg3Array != null) {
            // keep only first occurrence of .
            //  and the number of places specified by decimalPlaces or the entire string if decimalPlaces < 0
            var reg3Right = temp.substring(reg3Array.index + reg3Array[0].length);
            reg3Right = reg3Right.replace(reg3, '');
            reg3Right = decimalPlaces > 0 ? reg3Right.substring(0, decimalPlaces) : reg3Right;
            temp = temp.substring(0,reg3Array.index) + '.' + reg3Right;
        }
    }

    obj.value = temp;
}
function blockNonNumbers(obj, e, allowDecimal, allowNegative)
{
    var key;
    var isCtrl = false;
    var keychar;
    var reg;
    if(window.event) {
        key = e.keyCode;
        isCtrl = window.event.ctrlKey
    }
    else if(e.which) {
        key = e.which;
        isCtrl = e.ctrlKey;
    }

    if (isNaN(key)) return true;

    keychar = String.fromCharCode(key);

    // check for backspace or delete, or if Ctrl was pressed
    if (key == 8 || isCtrl)
    {
        return true;
    }

    reg = /\d/;
    var isFirstN = allowNegative ? keychar == '-' && obj.value.indexOf('-') == -1 : false;
    var isFirstD = allowDecimal ? keychar == '.' && obj.value.indexOf('.') == -1 : false;
    var isFirstC = allowDecimal ? keychar == ',' && obj.value.indexOf(',') == -1 : false;
    return isFirstN || isFirstD || isFirstC || reg.test(keychar);
}
function blockInvalid(obj)
{
    var temp=obj.value;
    if(temp=="-")
    {
        temp="";
    }

    if (temp.indexOf(".")==temp.length-1 && temp.indexOf(".")!=-1)
    {
        temp=temp+"00";
    }
    if (temp.indexOf(".")==0)
    {
        temp="0"+temp;
    }
    if (temp.indexOf(".")==1 && temp.indexOf("-")==0)
    {
        temp=temp.replace("-","-0") ;
    }
    if (temp.indexOf(",")==temp.length-1 && temp.indexOf(",")!=-1)
    {
        temp=temp+"00";
    }
    if (temp.indexOf(",")==0)
    {
        temp="0"+temp;
    }
    if (temp.indexOf(",")==1 && temp.indexOf("-")==0)
    {
        temp=temp.replace("-","-0") ;
    }
    temp=temp.replace(",",".") ;
    obj.value=temp;
}
// end of price text-box allow numeric and allow 2 decimal points only
</script>

<input type="Text" id="id" value="" onblur="extractNumber(this,2,true);blockInvalid(this);" onkeyup="extractNumber(this,2,true);" onkeypress="return blockNonNumbers(this, event, true, true);">
1
ответ дан Fathi Amin 3 September 2018 в 14:58
поделиться

Все решения, представленные здесь, используют события с одним ключом. Это очень подвержено ошибкам, поскольку ввод также может быть задан с помощью copy'n'paste или drag'n'drop. Также некоторые из решений ограничивают использование несимметричных клавиш, таких как ctrl+c, Pos1 и т. Д.

Я предлагаю, а не проверять каждое нажатие клавиши, проверяя, является ли результат действительным в отношении ваших ожиданий .

var validNumber = new RegExp(/^\d*\.?\d*$/);
var lastValid = document.getElementById("test1").value;
function validateNumber(elem) {
  if (validNumber.test(elem.value)) {
    lastValid = elem.value;
  } else {
    elem.value = lastValid;
  }
}
<textarea id="test1" oninput="validateNumber(this);" ></textarea>

Событие oninput запускается сразу после того, как что-то было изменено в текстовой области и перед визуализацией.

Вы можете расширить RegEx до любого формата, который вы хотите принять. Это намного удобнее и удобнее, чем проверка одиночных нажатий клавиш.

4
ответ дан Hubert Grzeskowiak 3 September 2018 в 14:58
поделиться
<input type="text" class="number_only" />    
<script>
$(document).ready(function() {
    $('.number_only').keypress(function (event) {
        return isNumber(event, this)
    });        
});

function isNumber(evt, element) {
    var charCode = (evt.which) ? evt.which : event.keyCode

    if ((charCode != 45 || $(element).val().indexOf('-') != -1) && (charCode != 46 || $(element).val().indexOf('.') != -1) && ((charCode < 48 && charCode != 8) || charCode > 57)){
        return false;
    }
    else {
        return true;
    }
} 
</script>

http://www.encodedna.com/2013/05/enter-only-numbers-using-jquery.htm

-1
ответ дан Igoris Azanovas 3 September 2018 в 14:58
поделиться

Работая над проблемой самостоятельно, и это то, что у меня есть до сих пор. Это более или менее работает, но после этого невозможно добавить минус из-за новой проверки значения. Также не разрешает запятую как разделитель тысяч, только десятичную.

Это не идеально, но может дать некоторые идеи.

app.directive('isNumber', function () {
            return function (scope, elem, attrs) {
                elem.bind('keypress', function (evt) {
                    var keyCode = (evt.which) ? evt.which : event.keyCode;
                    var testValue = (elem[0].value + String.fromCharCode(keyCode) + "0").replace(/ /g, ""); //check ignores spaces
                    var regex = /^\-?\d+((\.|\,)\d+)?$/;                        
                    var allowedChars = [8,9,13,27,32,37,39,44,45, 46] //control keys and separators             

                   //allows numbers, separators and controll keys and rejects others
                    if ((keyCode > 47 && keyCode < 58) || allowedChars.indexOf(keyCode) >= 0) {             
                        //test the string with regex, decline if doesn't fit
                        if (elem[0].value != "" && !regex.test(testValue)) {
                            event.preventDefault();
                            return false;
                        }
                        return true;
                    }
                    event.preventDefault();
                    return false;
                });
            };
        });

Позволяет:

11 11 .245 (в контроллере, отформатированном при размытии до 1111.245)

11,44

- 123.123

-1 014

0123 (отформатирован на размытие до 123)

не позволяет:

! @ # $ / *

abc

11.11.1

11,11.1

.42

0
ответ дан Jane Doe 3 September 2018 в 14:58
поделиться

Предположим, ваше имя поля текстового поля Income Вызовите этот метод проверки, когда вам нужно проверить свое поле:

function validate() {
    var currency = document.getElementById("Income").value;
      var pattern = /^[1-9]\d*(?:\.\d{0,2})?$/ ;
    if (pattern.test(currency)) {
        alert("Currency is in valid format");
        return true;
    } 
        alert("Currency is not in valid format!Enter in 00.00 format");
        return false;
}
1
ответ дан jcsanyi 3 September 2018 в 14:58
поделиться

Просто нужно применить этот метод в JQuery, и вы можете проверить свое текстовое поле, чтобы просто принять число с десятичной точностью.

function IsFloatOnly(element) {    
var value = $(element).val(); 
var regExp ="^\\d+(\\.\\d+)?$";
return value.match(regExp); 
}

См. рабочую демонстрацию здесь

4
ответ дан Jitender Kumar 3 September 2018 в 14:58
поделиться
function integerwithdot(s, iid){
        var i;
        s = s.toString();
        for (i = 0; i < s.length; i++){
            var c;
            if (s.charAt(i) == ".") {
            } else {
                c = s.charAt(i);
            }
            if (isNaN(c)) {
                c = "";
                for(i=0;i<s.length-1;i++){
                    c += s.charAt(i);
                }
                document.getElementById(iid).value = c;
                return false;
            }
        }
        return true;
    }
1
ответ дан Jonas Reycian 3 September 2018 в 14:58
поделиться
<input type="text" onkeypress="return isNumberKey(event,this)">

<script>
   function isNumberKey(evt, obj) {

            var charCode = (evt.which) ? evt.which : event.keyCode
            var value = obj.value;
            var dotcontains = value.indexOf(".") != -1;
            if (dotcontains)
                if (charCode == 46) return false;
            if (charCode == 46) return true;
            if (charCode > 31 && (charCode < 48 || charCode > 57))
                return false;
            return true;
        }


</script>
0
ответ дан Karthik 3 September 2018 в 14:58
поделиться
inputelement.onchange= inputelement.onkeyup= function isnumber(e){
    e= window.event? e.srcElement: e.target;
    while(e.value && parseFloat(e.value)+''!= e.value){
            e.value= e.value.slice(0, -1);
    }
}
1
ответ дан kennebec 3 September 2018 в 14:58
поделиться

Небольшая поправка к блестящему ответу @ rebisco для правильной проверки десятичного числа.

function isNumberKey(evt) {
    debugger;
    var charCode = (evt.which) ? evt.which : event.keyCode;
    if (charCode == 46 && evt.srcElement.value.split('.').length>1) {
        return false;
    }
    if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57))
        return false;
    return true;
}
2
ответ дан Kishore Kumar 3 September 2018 в 14:58
поделиться

Вот еще одно решение, которое допускает десятичные числа, а также ограничивает цифры после десятичной до двух знаков после запятой.

function isNumberKey(evt, element) {
  var charCode = (evt.which) ? evt.which : event.keyCode
  if (charCode > 31 && (charCode < 48 || charCode > 57) && !(charCode == 46 || charCode == 8))
    return false;
  else {
    var len = $(element).val().length;
    var index = $(element).val().indexOf('.');
    if (index > 0 && charCode == 46) {
      return false;
    }
    if (index > 0) {
      var CharAfterdot = (len + 1) - index;
      if (CharAfterdot > 3) {
        return false;
      }
    }

  }
  return true;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" id="rate" placeholder="Billing Rate" required onkeypress="return isNumberKey(event,this)">

10
ответ дан Kurenai Kunai 3 September 2018 в 14:58
поделиться

Вы ищете что-то вроде этого?

   <HTML>
   <HEAD>
   <SCRIPT language=Javascript>
      <!--
      function isNumberKey(evt)
      {
         var charCode = (evt.which) ? evt.which : event.keyCode
         if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57))
            return false;

         return true;
      }
      //-->
   </SCRIPT>
   </HEAD>
   <BODY>
      <INPUT id="txtChar" onkeypress="return isNumberKey(event)" type="text" name="txtChar">
   </BODY>
  </HTML>
4
ответ дан lak-b 3 September 2018 в 14:58
поделиться

Лучшее и работающее решение с образцом Pure-Javascript Live demo: https://jsfiddle.net/manoj2010/ygkpa89o/

<script>
function removeCommas(nStr) {
    if (nStr == null || nStr == "")
        return ""; 
    return nStr.toString().replace(/,/g, "");
}

function NumbersOnly(myfield, e, dec,neg)
{        
    if (isNaN(removeCommas(myfield.value)) && myfield.value != "-") {
        return false;
    }
    var allowNegativeNumber = neg || false;
    var key;
    var keychar;

    if (window.event)
        key = window.event.keyCode;
    else if (e)
        key = e.which;
    else
        return true;
    keychar = String.fromCharCode(key);
    var srcEl = e.srcElement ? e.srcElement : e.target;    
    // control keys
    if ((key == null) || (key == 0) || (key == 8) ||
                (key == 9) || (key == 13) || (key == 27))
        return true;

    // numbers
    else if ((("0123456789").indexOf(keychar) > -1))
        return true;

    // decimal point jump
    else if (dec && (keychar == ".")) {
        //myfield.form.elements[dec].focus();
        return srcEl.value.indexOf(".") == -1;        
    }

    //allow negative numbers
    else if (allowNegativeNumber && (keychar == "-")) {    
        return (srcEl.value.length == 0 || srcEl.value == "0.00")
    }
    else
        return false;
}
</script>
<input name="txtDiscountSum" type="text" onKeyPress="return NumbersOnly(this, event,true)" /> 

0
ответ дан Manoj Prajapat 3 September 2018 в 14:58
поделиться

Для тех, кто спотыкается здесь, как я, вот версия jQuery 1.10.2, которую я написал, которая работает очень хорошо для меня, хотя и ресурсоемкой:

/***************************************************
* Only allow numbers and one decimal in text boxes
***************************************************/
$('body').on('keydown keyup keypress change blur focus paste', 'input[type="text"]', function(){
    var target = $(this);

    var prev_val = target.val();

    setTimeout(function(){
        var chars = target.val().split("");

        var decimal_exist = false;
        var remove_char = false;

        $.each(chars, function(key, value){
            switch(value){
                case '0':
                case '1':
                case '2':
                case '3':
                case '4':
                case '5':
                case '6':
                case '7':
                case '8':
                case '9':
                case '.':
                    if(value === '.'){
                        if(decimal_exist === false){
                            decimal_exist = true;
                        }
                        else{
                            remove_char = true;
                            chars[''+key+''] = '';
                        }
                    }
                    break;
                default:
                    remove_char = true;
                    chars[''+key+''] = '';
                    break;
            }
        });

        if(prev_val != target.val() && remove_char === true){
            target.val(chars.join(''))
        }
    }, 0);
});
2
ответ дан MonkeyZeus 3 September 2018 в 14:58
поделиться

альтернативный способ ограничить ввод текстового поля, чтобы он принимал только числа, а десятичная точка - использовать javascript внутри входа html. Это работает для меня:

<input type="text" class="form-control" id="price" name="price" placeholder="Price" 
vrequired onkeyup="this.value=this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1')">

- Принимает -

9

9.99

- Не принимать--

9.99.99

ABC

0
ответ дан mpalencia 3 September 2018 в 14:58
поделиться
form.onsubmit = function(){
    return textarea.value.match(/^\d+(\.\d+)?$/);
}

Это то, что вы ищете?

Надеюсь, это поможет.

EDIT: Я отредактировал свой пример выше, чтобы мог быть только один период, которому предшествует по крайней мере одна цифра, за которой следует, по меньшей мере, одна цифра.

24
ответ дан Norman H 3 September 2018 в 14:58
поделиться

Если вы хотите его для значений float,

Вот функция, которую я использую

<HTML>

<HEAD>
  <SCRIPT language=Javascript>
    <!--
    function check(e, value) {
      //Check Charater
      var unicode = e.charCode ? e.charCode : e.keyCode;
      if (value.indexOf(".") != -1)
        if (unicode == 46) return false;
      if (unicode != 8)
        if ((unicode < 48 || unicode > 57) && unicode != 46) return false;
    }
    //-->
  </SCRIPT>
</HEAD>

<BODY>
  <INPUT id="txtChar" onkeypress="return check(event,value)" type="text" name="txtChar">
</BODY>

</HTML>

0
ответ дан rahulsm 3 September 2018 в 14:58
поделиться

Расширение ответа @ rebisco. этот ниже код будет содержать только цифры и одиночный '.' (период) в текстовом поле.

function isNumberKey(evt) {
        var charCode = (evt.which) ? evt.which : event.keyCode;
        if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57)) {
            return false;
        } else {
            // If the number field already has . then don't allow to enter . again.
            if (evt.target.value.search(/\./) > -1 && charCode == 46) {
                return false;
            }
            return true;
        }
    }
1
ответ дан Santosh Kurdekar 3 September 2018 в 14:58
поделиться
document.getElementById('value').addEventListener('keydown', function(e) {
    var key   = e.keyCode ? e.keyCode : e.which;

/*lenght of value to use with index to know how many numbers after.*/

    var len = $('#value').val().length;
    var index = $('#value').val().indexOf('.');
    if (!( [8, 9, 13, 27, 46, 110, 190].indexOf(key) !== -1 ||
                    (key == 65 && ( e.ctrlKey || e.metaKey  ) ) ||
                    (key >= 35 && key <= 40) ||
                    (key >= 48 && key <= 57 && !(e.shiftKey || e.altKey)) ||
                    (key >= 96 && key <= 105)
            )){
        e.preventDefault();
    }

/*if theres a . count how many and if reachs 2 digits after . it blocks*/ 

    if (index > 0) {
        var CharAfterdot = (len + 1) - index;
        if (CharAfterdot > 3) {

/*permits the backsapce to remove :D could be improved*/

            if (!(key == 8))
            {
                e.preventDefault();
            }

/*blocks if you try to add a new . */

        }else if ( key == 110) {
            e.preventDefault();
        }

/*if you try to add a . and theres no digit yet it adds a 0.*/

    } else if( key == 110&& len==0){
        e.preventDefault();
        $('#value').val('0.');
    }
});
-1
ответ дан Thomas Ayoub 3 September 2018 в 14:58
поделиться

Я знаю, что этот вопрос очень старый, но все же мы часто получаем такие требования. Есть много примеров, однако многие, кажется, слишком многословны или сложны для простой импликации.

Смотрите https://jsfiddle.net/vibs2006/rn0fvxuk/ и улучшайте его (если можете). Он работает на IE, Firefox, Chrome и Edge Browser.

Вот рабочий код.

        
        function IsNumeric(e) {
        var IsValidationSuccessful = false;
        console.log(e.target.value);
        document.getElementById("info").innerHTML = "You just typed ''" + e.key + "''";
        //console.log("e.Key Value = "+e.key);
        switch (e.key)
         {         
             case "1":
             case "2":
             case "3":
             case "4":
             case "5":
             case "6":
             case "7":
             case "8":
             case "9":
             case "0":
             case "Backspace":             
                 IsValidationSuccessful = true;
                 break;
                 
						 case "Decimal":  //Numpad Decimal in Edge Browser
             case ".":        //Numpad Decimal in Chrome and Firefox                      
             case "Del": 			// Internet Explorer 11 and less Numpad Decimal 
                 if (e.target.value.indexOf(".") >= 1) //Checking if already Decimal exists
                 {
                     IsValidationSuccessful = false;
                 }
                 else
                 {
                     IsValidationSuccessful = true;
                 }
                 break;

             default:
                 IsValidationSuccessful = false;
         }
         //debugger;
         if(IsValidationSuccessful == false){
         
         document.getElementById("error").style = "display:Block";
         }else{
         document.getElementById("error").style = "display:none";
         }
         
         return IsValidationSuccessful;
        }
Numeric Value: <input type="number" id="text1" onkeypress="return IsNumeric(event);" ondrop="return false;" onpaste="return false;" /><br />
    <span id="error" style="color: Red; display: none">* Input digits (0 - 9) and Decimals Only</span><br />
    <div id="info"></div>

0
ответ дан vibs2006 3 September 2018 в 14:58
поделиться
Другие вопросы по тегам:

Похожие вопросы: