Limitazione dell'input alla casella di testo: consente solo numeri e virgola decimale


107

Come posso limitare l'input a una casella di testo in modo che accetti solo numeri e il punto decimale?


11
La sua domanda originale era fantastica, Amar ... !!! Perché cambiarlo ..? ;)
— SpikETidE

14
Perché i voti negativi? Il ragazzo è nuovo qui, aiutalo a migliorare le sue ricerche, per favore.
— lexu

Ayyappan.Anbalagan, aggiungi alcuni esempi al post :) Sono tutte queste stringhe corrette per te? 192192.168 192.168.0.1
— lak-b

ho capito amico ... solo il formato 22.22 dovrebbe consentire solo 5 caratteri nella casella di testo ...
— TinTin

Qual è il problema con isNaN(this.textbox.value)??
— Sam007

Risposte:


158

<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>

Funziona davvero!


1
Perché è necessario && charCode> 31?
— contattare il

2
Il carattere 31 è il codice separatore unità. Praticamente i numeri e il testo sono compresi tra 32 e più. Il codice dice che se il codice carattere inserito non è il decimale AND è maggiore di 31 (separatore di unità) ma minore di 48 (numero zero) o maggiore di 57 (numero nove), non accettarlo.
— Paul Williams

9
if (charCode == 46 && evt.srcElement.value.split ('.'). length> 1) {return false; } Sarà privato di più "." ... :)
— Anish Karunakaran

10
includere tasti numerici e punti del tastierino con:&& charCode != 190 && charCode != 110 && (charCode > 105 || charCode < 96)
— mga

1
sta accettando più di uno '. [punto] ", che credo sia sbagliato.
— Akshay Chawla

26
form.onsubmit = function(){
    return textarea.value.match(/^\d+(\.\d+)?$/);
}

È questo quello che stai cercando?

Spero possa essere d'aiuto.

EDIT: ho modificato il mio esempio sopra in modo che possa esserci un solo punto, preceduto da almeno una cifra e seguito da almeno una cifra.


1
Penso che questo convaliderà anche '99 .23.65.86 '.... Ma immagino che la domanda riguardasse la convalida di' 56987.32 'con un singolo punto .....
— SpikETidE

vedo che il poster da allora ha modificato la sua domanda originale. grazie per l'aggiornamento!
— tau

1
È meglio usare /^\d+([\.,”\d+)?$/ per supportare i numeri internazionali (dove viene utilizzata la virgola al posto del punto)
— FDIM

26

La soluzione accettata non è completa, poiché è possibile immettere più ".", Ad esempio 24 .... 22..22. con alcune piccole modifiche funzionerà come previsto:

<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>


Ho usato la tua risposta ma ho modificato questo onkeypress = "return isNumberKey (this, event);"
— Bilbo Baggins

sì, penso che sia facoltativo digitare passa l'evento, poiché funziona con entrambi i casi, grazie
— Hassan Mokdad

ci ha risparmiato alcuni colpi di chiave .. tq
— Irf

l'unico problema con questo è che puoi copiare e incollare nel testo. L'aggiunta all'elemento di input ondrop="return false;" onpaste="return false;" oncontextmenu="return false;"sembra essere sufficiente
— clamchoda

È un cattivo servizio per ogni utente impedire loro di utilizzare il trascinamento della selezione o il copia e incolla.
— Hubert Grzeskowiak

19

Ecco un'altra soluzione che consente i numeri decimali e limita anche le cifre dopo i decimali a 2 cifre decimali.

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)">


Quasi perfetto .. l'ultima condizione della tua ifmanca la "C" maiuscola.
— DNKROZ

Bella soluzione !!
— Michael Murray

Beutiful. Funziona perfettamente per me.
— Noor Ahmed

Notare che questa soluzione consente più punti ( .), trattino ( -) e la lettera equando il testo viene incollato o rilasciato nel campo. L'elemento HTML mostrerà anche due frecce per aumentare e diminuire il numero per impostazione predefinita in Chrome. Il pulsante di diminuzione consente al numero di scendere sotto lo zero.
— Hubert Grzeskowiak

12

Tutte le soluzioni presentate qui utilizzano singoli eventi chiave. Questo è molto soggetto a errori poiché l'input può essere fornito anche usando copy'n'paste o drag'n'drop. Inoltre alcune delle soluzioni limitano l'uso di chiavi non di carattere come ctrl+c, Pos1ecc.

Suggerisco invece di controllare ogni pressione dei tasti di controllare se il risultato è valido rispetto alle vostre aspettative.

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>

L' oninputevento viene attivato subito dopo che qualcosa è stato modificato nell'area di testo e prima di essere renderizzato.

Puoi estendere la RegEx a qualsiasi formato di numero che desideri accettare. Questo è molto più gestibile ed estendibile rispetto al controllo della pressione di un singolo tasto.


Questa è la soluzione più elegante!
— jkd

4

Cerchi qualcosa di simile?

   <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

Devi solo applicare questo metodo in Jquery e puoi convalidare la tua casella di testo per accettare solo il numero con solo un decimale.

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

Si prega di vedere la demo di lavoro qui


2

Per chiunque inciampi qui come ho fatto io, ecco una versione di jQuery 1.10.2 che ho scritto che funziona molto bene per me anche se ad alta intensità di risorse:

/***************************************************
* 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

Una piccola correzione alla brillante risposta di @ rebisco per convalidare perfettamente il decimale.

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;
}

questo va molto bene. Tuttavia, vorrei limitarlo a 2 punti decimali, comunque per farlo?
— nodeffect

2

Se lo vuoi per valori float,

Ecco la funzione che sto usando

<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>


1
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
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

ecco lo script che ti aiuta:

<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

Supponiamo che il nome del campo della casella di testo sia Income
Chiama questo metodo di convalida quando è necessario convalidare il campo:

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

Estendere la risposta di @ rebisco. il codice sottostante consentirà solo numeri e un singolo "." (punto) nella casella di testo.

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

Soluzione migliore

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

    if(event.target.value.indexOf('.') >=0 && charCode == 46)
        return false;

    return true;
}

0

A partire dalla risposta di @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;
}

Consente solo questo formato: 123123123 [.121213]

Demo qui demo


0

Spero che funzioni per te.

<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>

0

Il codice seguente ha funzionato per me

La casella di input con l'evento "onkeypress" come segue

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

La funzione "isNumberKey" è la seguente

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

Ho osservato che per tutte le risposte fornite qui, le cose non funzionano se selezioniamo una parte del testo nella casella di testo e proviamo a sovrascrivere quella parte. Quindi ho modificato la funzione che è la seguente:

    <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

Per i numeri decimali e consentendo anche numeri negativi con 2 posizioni per i decimali dopo il punto ... ho modificato la funzione in:

<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

Un modo alternativo per limitare l'input a una casella di testo in modo che accetti solo numeri e il punto decimale è usare javascript all'interno dell'input html. Questo funziona per me:

<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')">

--Accepts--

9

9.99

--Non accetto--

9.99.99

ABC


0
function isNumberKey(evt)
{
    var charCode = (evt.which) ? evt.which : evt.keyCode;

    if(charCode==8 || charCode==13|| charCode==99|| charCode==118 || charCode==46)
    {    
        return true;  
    }

    if (charCode > 31 && (charCode < 48 || charCode > 57))
    {   
        return false; 
    }
    return true;
}

Consentirà solo valori numerici e ti permetterà di inserire "." per decimale.


0
<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)})

Funziona bene.


0

Soluzione migliore e funzionante con demo live di esempio Pure-Javascript: 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

Sto lavorando da solo sulla questione, ed è quello che ho ottenuto finora. Questo più o meno funziona, ma è impossibile aggiungere meno in seguito a causa del nuovo controllo del valore. Inoltre non consente la virgola come separatore di migliaia, solo decimale.

Non è perfetto, ma potrebbe dare qualche idea.

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;
                });
            };
        });

permette:

11 11 .245 (nel controller formattato su sfocatura a 1111.245)

11,44

-123,123

-1 014

0123 (formattato su sfocatura a 123)

non consente:

! @ # $ / *

abc

11.11.1

11,11.1

.42


0
<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

So che questa domanda è molto vecchia, ma spesso riceviamo tali requisiti. Ci sono molti esempi, ma molti sembrano essere troppo prolissi o complessi per una semplice impiantazione.

Vedi questo https://jsfiddle.net/vibs2006/rn0fvxuk/ e miglioralo (se puoi). Funziona su IE, Firefox, Chrome e Edge Browser.

Ecco il codice funzionante.

        
        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

Ho scelto di affrontare questo problema durante l' oninputevento al fine di gestire il problema di incollare la tastiera, incollare il mouse e premere i tasti. Passa true o false per indicare la convalida decimale o intera.

Sono fondamentalmente tre passaggi in tre una riga. Se non vuoi troncare i decimali commenta il terzo passaggio. Anche la terza fase può essere regolata per l'arrotondamento.

// Example Decimal usage;
// <input type="text"  oninput="ValidateNumber(this, true);" />
// Example Integer usage:
// <input type="text"  oninput="ValidateNumber(this, false);" />
function ValidateNumber(elm, isDecimal) {
    try {

        // For integers, replace everything except for numbers with blanks.
        if (!isDecimal) 
            elm.value = elm.value.replace(/[^0-9]/g, ''); 
        else {
            // 1. For decimals, replace everything except for numbers and periods with blanks.
            // 2. Then we'll remove all leading ocurrences (duplicate) periods
            // 3. Then we'll chop off anything after two decimal places.

            // 1. replace everything except for numbers and periods with blanks.
            elm.value = elm.value.replace(/[^0-9.]/g, '');

            //2. remove all leading ocurrences (duplicate) periods
            elm.value = elm.value.replace(/\.(?=.*\.)/g, '');

            // 3. chop off anything after two decimal places.
            // In comparison to lengh, our index is behind one count, then we add two for our decimal places.
            var decimalIndex = elm.value.indexOf('.');
            if (decimalIndex != -1) { elm.value = elm.value.substr(0, decimalIndex + 3); }
        }
    }
    catch (err) {
        alert("ValidateNumber " + err);
    }
}

0
<input type="text" onkeypress='return event.charCode >= 48 && event.charCode <= 57'>

È possibile limitare i valori da inserire dall'utente specificando l'intervallo di valori ASCII.
Esempio : da 48 a 57 per i valori numerici (da 0 a 9)

Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.