Domanda

Esiste un modo rapido per impostare un input di testo HTML (<input type=text />) per consentire solo sequenze di tasti numeriche (più '.')?

È stato utile?

Soluzione

Nota: questa è una risposta aggiornata. I commenti che seguono si riferiscono a una versione precedente che si è comportata in modo scorretto con i codici chiave

JavaScript

La funzione setInputFilter di seguito consente di utilizzare qualsiasi tipo di filtro di input su un < input > di testo, inclusi vari filtri numerici ( vedi sotto).

A differenza della maggior parte delle altre soluzioni, questo supporta correttamente Copia + Incolla, Trascina + Rilascia, tutte le scorciatoie da tastiera, tutte le operazioni del menu contestuale, tutti i tasti non digitabili (ad es. cursore e tasti di navigazione), il cursore posizione, tutti i layout di tastiera di tutte le lingue e piattaforme e tutti i browser da IE 9 .

Provalo tu stesso su JSFiddle .

// Restricts input for the given textbox to the given inputFilter.
function setInputFilter(textbox, inputFilter) {
  ["input", "keydown", "keyup", "mousedown", "mouseup", "select", "contextmenu", "drop"].forEach(function(event) {
    textbox.addEventListener(event, function() {
      if (inputFilter(this.value)) {
        this.oldValue = this.value;
        this.oldSelectionStart = this.selectionStart;
        this.oldSelectionEnd = this.selectionEnd;
      } else if (this.hasOwnProperty("oldValue")) {
        this.value = this.oldValue;
        this.setSelectionRange(this.oldSelectionStart, this.oldSelectionEnd);
      }
    });
  });
}

// Restrict input to digits and '.' by using a regular expression filter.
setInputFilter(document.getElementById("myTextBox"), function(value) {
  return /^\d*\.?\d*$/.test(value);
});

Alcuni filtri di input che potresti voler utilizzare:

  • Numeri interi (solo positivi):
    / ^ \ d * $ /. Di prova (valore)
  • Integer valori (positivi e fino a un limite particolare):
    /^\d*$/.test(value) & amp; & amp; (valore === " " || parseInt (valore) < = 500)
  • Numero intero (sia positivo che negativo):
    / ^ -?. \ D * $ / test (valore)
  • Virgola mobile (consentendo sia . che , come separatore decimale):
    Tag / ^ -? [.,]. \ D * \ d * $ / test (valore)
  • Valori
  • Valuta (ovvero al massimo due cifre decimali):
    / ^ -? [.,]. \ D * \ d {0,2} $ / test (valore)
  • Solo
  • A-Z (ovvero lettere latine di base):
    / ^ [a-z] * $ / i.test (valore)
  • lettere latine (ovvero inglese e la maggior parte delle lingue europee, vedi https: // tabella unicode .com per dettagli sulle gamme di caratteri Unicode):
    / ^ [a-z \ u00c0- \ u024f] * $ / i.test (valore)
  • Valori
  • esadecimali :
    / ^ [0-9a-f] * $ / i.test (valore)

Nota che devi ancora eseguire la convalida sul lato server!

jQuery

Esiste anche una versione jQuery di questo. Vedi questa risposta o provalo tu stesso su JSFiddle .

HTML 5

HTML 5 ha una soluzione nativa con < input type = " number " > (vedi specifica ), ma il supporto del browser varia:

  • La maggior parte dei browser convalida l'input solo quando invia il modulo e non durante la digitazione.
  • La maggior parte dei browser mobili non supporta il passaggio , min e max .
  • Chrome (versione 71.0.3578.98) consente comunque all'utente di inserire i caratteri e e E nel campo. Vedi anche questa domanda .
  • Firefox (versione 64.0) e Edge (EdgeHTML versione 17.17134) consentono ancora all'utente di inserire qualsiasi testo nel campo.

Provalo tu stesso su w3schools.com .

Altri suggerimenti

Usa questo DOM

<input type='text' onkeypress='validate(event)' />

E questo script

function validate(evt) {
  var theEvent = evt || window.event;

  // Handle paste
  if (theEvent.type === 'paste') {
      key = event.clipboardData.getData('text/plain');
  } else {
  // Handle key press
      var key = theEvent.keyCode || theEvent.which;
      key = String.fromCharCode(key);
  }
  var regex = /[0-9]|\./;
  if( !regex.test(key) ) {
    theEvent.returnValue = false;
    if(theEvent.preventDefault) theEvent.preventDefault();
  }
}

Ho cercato a lungo e duramente una buona risposta a questo, e abbiamo disperatamente bisogno di < input type = " number " , ma a parte questo, questi 2 sono i modi più concisi Potrei venire con:

<input type="text" 
       onkeyup="this.value=this.value.replace(/[^\d]/,'')">

Se non ti piace il carattere non accettato mostrato per una frazione di secondo prima di essere cancellato, il metodo di seguito è la mia soluzione. Nota le numerose condizioni aggiuntive, questo per evitare di disabilitare tutti i tipi di navigazione e tasti di scelta rapida. Se qualcuno sa come compattarlo, faccelo sapere!

<input type="text" 
onkeydown="return ( event.ctrlKey || event.altKey 
                    || (47<event.keyCode && event.keyCode<58 && event.shiftKey==false) 
                    || (95<event.keyCode && event.keyCode<106)
                    || (event.keyCode==8) || (event.keyCode==9) 
                    || (event.keyCode>34 && event.keyCode<40) 
                    || (event.keyCode==46) )">

Eccone uno semplice che consente esattamente un decimale, ma non di più:

<input type="text" oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1');" />

E un altro esempio, che funziona benissimo per me:

function validateNumber(event) {
    var key = window.event ? event.keyCode : event.which;
    if (event.keyCode === 8 || event.keyCode === 46) {
        return true;
    } else if ( key < 48 || key > 57 ) {
        return false;
    } else {
        return true;
    }
};

Allega anche all'evento keypress

$(document).ready(function(){
    $('[id^=edit]').keypress(validateNumber);
});

E HTML:

<input type="input" id="edit1" value="0" size="5" maxlength="5" />

Ecco un esempio di jsFiddle

HTML5 ha < input type = number > , che suona bene per te. Attualmente, solo Opera lo supporta in modo nativo, ma esiste un progetto che ha un'implementazione JavaScript.

La maggior parte delle risposte qui ha tutti il ??punto debole nell'utilizzo di eventi chiave .

Molte delle risposte limiterebbero la tua capacità di fare la selezione del testo con macro della tastiera, copia + incolla e comportamenti più indesiderati, altri sembrano dipendere da specifici plugin jQuery, che sta uccidendo le mosche con le mitragliatrici.

Questa semplice soluzione sembra funzionare meglio per me multipiattaforma, indipendentemente dal meccanismo di input (sequenza di tasti, copia + incolla, copia + incolla con il tasto destro, sintesi vocale, ecc.). Tutte le macro della tastiera per la selezione del testo continuerebbero a funzionare e limiterebbero persino la possibilità di impostare un valore non numerico tramite script.

function forceNumeric(){
    this.value(this.value.replace(/[^\d]+/g,''));
}
$('body').on('propertychange input', 'input.numeric-text', forceNumeric);

Ho scelto di utilizzare una combinazione delle due risposte menzionate qui, ad esempio

< input type = " number " / & Gt;

e

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

< input type = " text " onkeypress = " return isNumberKey (evento); " >

HTML5 supporta regex, quindi puoi usare questo:

<input id="numbersOnly" pattern="[0-9.]+" type="text">

Avviso: alcuni browser non lo supportano ancora.

JavaScript

function validateNumber(evt) {
    var e = evt || window.event;
    var key = e.keyCode || e.which;

    if (!e.shiftKey && !e.altKey && !e.ctrlKey &&
    // numbers   
    key >= 48 && key <= 57 ||
    // Numeric keypad
    key >= 96 && key <= 105 ||
    // Backspace and Tab and Enter
    key == 8 || key == 9 || key == 13 ||
    // Home and End
    key == 35 || key == 36 ||
    // left and right arrows
    key == 37 || key == 39 ||
    // Del and Ins
    key == 46 || key == 45) {
        // input is VALID
    }
    else {
        // input is INVALID
        e.returnValue = false;
        if (e.preventDefault) e.preventDefault();
    }
}

aggiuntivo puoi aggiungere virgola, punto e meno (, .-)

  // comma, period and minus, . on keypad
  key == 190 || key == 188 || key == 109 || key == 110 ||

HTML

<input type="text" onkeydown="validateNumber(event);"/ >

2 soluzioni:

Utilizza un validatore di moduli (ad esempio con plugin di validazione jQuery )

Esegui un controllo durante l'evento onblur (ovvero quando l'utente lascia il campo) del campo di input, con l'espressione regolare:

<script type="text/javascript">
function testField(field) {
    var regExpr = new RegExp("^\d*\.?\d*<*>quot;);
    if (!regExpr.test(field.value)) {
      // Case of error
      field.value = "";
    }
}

</script>

<input type="text" ... onblur="testField(this);"/>

Così semplice ....

// In una funzione JavaScript (può usare HTML o PHP).

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

Nell'input del modulo:

<input type=text name=form_number size=20 maxlength=12 onkeypress='return isNumberKey(event)'>

Con ingresso max. (Questi sopra consentono un numero di 12 cifre)

Un approccio più sicuro sta controllando il valore dell'input, invece di dirottare i tasti premuti e provare a filtrare i KeyCode.

In questo modo l'utente è libero di usare le frecce della tastiera, i tasti modificatori, il backspace, l'eliminazione, l'uso di keyboar non standard, l'uso del mouse per incollare, l'uso del trascinamento della selezione del testo e persino l'uso di input di accessibilità.

Lo script seguente consente numeri positivi e negativi

1
10
100.0
100.01
-1
-1.0
-10.00
1.0.0 //not allowed

var input = document.getElementById('number');
input.onkeyup = input.onchange = enforceFloat;

//enforce that only a float can be inputed
function enforceFloat() {
  var valid = /^\-?\d+\.\d*$|^\-?[\d]*$/;
  var number = /\-\d+\.\d*|\-[\d]*|[\d]+\.[\d]*|[\d]+/;
  if (!valid.test(this.value)) {
    var n = this.value.match(number);
    this.value = n ? n[0] : '';
  }
}
<input id="number" value="-3.1415" placeholder="Type a number" autofocus>

EDIT: ho rimosso la mia vecchia risposta perché penso che ora sia antiquata.

Trova la soluzione di seguito indicata. In questo utente può essere in grado di inserire solo il valore numerico , inoltre l'utente non può essere in grado di copiare , incolla , trascinare e drop nell'input.

  

Personaggi consentiti

0,1,2,3,4,5,6,7,8,9
  

Personaggi e personaggi non consentiti attraverso eventi

  • Valore alfabetico
  • Caratteri speciali
  • Copia
  • Incolla
  • drag
  • Goccia

$(document).ready(function() {
  $('#number').bind("cut copy paste drag drop", function(e) {
      e.preventDefault();
  });     
});
function isNumberKey(evt) {
    var charCode = (evt.which) ? evt.which : evt.keyCode;
    if (charCode > 31 && (charCode < 48 || charCode > 57))
        return false;
    return true;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="text" class="form-control" name="number" id="number" onkeypress="return isNumberKey(event)" placeholder="Enter Numeric value only">

Fammi sapere se non funziona.

Puoi usare pattern per questo:

<input id="numbers" pattern="[0-9.]+" type="number">

Qui puoi vedere il suggerimenti completi sull'interfaccia del sito Web mobile .

Se vuoi suggerire al dispositivo (forse un telefono cellulare) tra alfa o numerico puoi usare < input type = " number " > .

Un'implementazione breve e dolce che utilizza jQuery e replace () invece di guardare event.keyCode o event.which:

$('input.numeric').live('keyup', function(e) {
  $(this).val($(this).val().replace(/[^0-9]/g, ''));
});

Solo un piccolo effetto collaterale del fatto che la lettera digitata appare momentaneamente e CTRL / CMD + A sembra comportarsi in modo un po 'strano.

Codice JavaScript:

function validate(evt)
{
    if(evt.keyCode!=8)
    {
        var theEvent = evt || window.event;
        var key = theEvent.keyCode || theEvent.which;
        key = String.fromCharCode(key);
        var regex = /[0-9]|\./;
        if (!regex.test(key))
        {
            theEvent.returnValue = false;

            if (theEvent.preventDefault)
                theEvent.preventDefault();
            }
        }
    }

Codice HTML:

<input type='text' name='price' value='0' onkeypress='validate(event)'/>

funziona perfettamente perché il codice tasto backspace è 8 e un'espressione regex non lo consente, quindi è un modo semplice per aggirare il bug :)

Solo un'altra variante con jQuery che utilizza

$(".numeric").keypress(function() {
    return (/\d/.test(String.fromCharCode(event.which) ))
});

input type = " number " è un attributo HTML5.

Nell'altro caso questo ti aiuterà:

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

<input type="number" name="somecode" onkeypress="return isNumberKey(event)"/>

Un altro esempio in cui puoi aggiungere solo numeri nel campo di input, non puoi lettere

<input type="text" class="form-control" id="phone" name="phone" placeholder="PHONE" spellcheck="false" oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1');">

usa type = " number " ora questo attributo supporta la maggior parte dei browser

<input type="number" maxlength="3" ng-bind="first">

Puoi anche confrontare il valore di input (che è trattato come stringa di default) con se stesso forzato come numerico, come:

if(event.target.value == event.target.value * 1) {
    // returns true if input value is numeric string
}

Tuttavia, è necessario associarlo a eventi come keyup ecc.

<input name="amount" type="text" value="Only number in here"/> 

<script>
    $('input[name=amount]').keyup(function(){
        $(this).val($(this).val().replace(/[^\d]/,''));
    });
</script>

Usa questo DOM:

<input type = "text" onkeydown = "validate(event)"/>

E questo script:

validate = function(evt)
{
    if ([8, 46, 37, 39, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 35, 36].indexOf(evt.keyCode || evt.which) == -1)
    {
        evt.returnValue = false;
        if(evt.preventDefault){evt.preventDefault();}
    }
}

... O questo script, senza indexOf, usando due per 's ...

validate = function(evt)
{
    var CharValidate = new Array("08", "046", "039", "948", "235");
    var number_pressed = false;
    for (i = 0; i < 5; i++)
    {
        for (Ncount = 0; Ncount < parseInt(CharValidate[i].substring(0, 1)) + 1; Ncount++)
        {
            if ((evt.keyCode || evt.which) == parseInt(CharValidate[i].substring(1, CharValidate[i].lenght)) + Ncount)
            {
                number_pressed = true;
            }
        }
    }
    if (number_pressed == false)
    {
        evt.returnValue = false;
        if(evt.preventDefault){evt.preventDefault();}
    }
}

Ho usato l'attributo onkeydown invece di onkeypress, perché l'attributo onkeydown è controllato prima dell'attributo onkeypress. Il problema sarebbe nel browser Google Chrome.

Con l'attributo "onkeypress", TAB sarebbe incontrollabile con "preventDefault" su google chrome, tuttavia, con l'attributo " onkeydown " ;, TAB diventa controllabile!

Codice ASCII per TAB = > 9

Il primo script ha meno codice del secondo, tuttavia, l'array di caratteri ASCII deve avere tutte le chiavi.

Il secondo script è molto più grande del primo, ma l'array non ha bisogno di tutte le chiavi. La prima cifra in ciascuna posizione dell'array è il numero di volte in cui ogni posizione verrà letta. Per ogni lettura, verrà incrementato di 1 a quello successivo. Per esempio:




NCount = 0

48 + NCount = 48

NCount + +

48 + NCount = 49

NCount + +

...

48 + NCount = 57




Nel caso delle chiavi numeriche sono solo 10 (0 - 9), ma se fossero 1 milione non avrebbe senso creare un array con tutte queste chiavi.

Codici ASCII:

  • 8 == > (Backspace);
  • 46 = > (Delete);
  • 37 = > (freccia sinistra);
  • 39 = > (freccia destra);
  • 48 - 57 = > (Numeri);
  • 36 = > (Casa);
  • 35 = > (Fine);

Questa è una funzione migliorata:

function validateNumber(evt) {
  var theEvent = evt || window.event;
  var key = theEvent.keyCode || theEvent.which;
  if ((key < 48 || key > 57) && !(key == 8 || key == 9 || key == 13 || key == 37 || key == 39 || key == 46) ){
    theEvent.returnValue = false;
    if (theEvent.preventDefault) theEvent.preventDefault();
  }
}

Il modo migliore (consenti TUTTI i tipi di numeri - reale negativo, reale positivo, intero negativo, intero positivo) è:

$(input).keypress(function (evt){
    var theEvent = evt || window.event;
    var key = theEvent.keyCode || theEvent.which;
    key = String.fromCharCode( key );
    var regex = /[-\d\.]/; // dowolna liczba (+- ,.) :)
    var objRegex = /^-?\d*[\.]?\d*$/;
    var val = $(evt.target).val();
    if(!regex.test(key) || !objRegex.test(val+key) || 
            !theEvent.keyCode == 46 || !theEvent.keyCode == 8) {
        theEvent.returnValue = false;
        if(theEvent.preventDefault) theEvent.preventDefault();
    };
}); 

Questa è la versione estesa di la soluzione di geowa4 . Supporta gli attributi min e max . Se il numero non rientra nell'intervallo, verrà visualizzato il valore precedente.

Puoi provarlo qui.

Utilizzo: < input type = text class = 'number' maxlength = 3 min = 1 max = 500 >

function number(e) {
var theEvent = e || window.event;
var key = theEvent.keyCode || theEvent.which;
if(key!=13&&key!=9){//allow enter and tab
  key = String.fromCharCode( key );
  var regex = /[0-9]|\./;
  if( !regex.test(key)) {
    theEvent.returnValue = false;
    if(theEvent.preventDefault) theEvent.preventDefault();
    }   
  }
}

$(document).ready(function(){
    $("input[type=text]").filter(".number,.NUMBER").on({
        "focus":function(e){
         $(e.target).data('oldValue',$(e.target).val());
            },
        "keypress":function(e){
                e.target.oldvalue = e.target.value;
                number(e);
            },
        "change":function(e){
            var t = e.target;
            var min = $(t).attr("min");
            var max = $(t).attr("max");
            var val = parseInt($(t).val(),10);          
            if( val<min || max<val)
                {
                    alert("Error!");
                    $(t).val($(t).data('oldValue'));
                }

            }       
    });     
});

Se gli input sono dinamici, utilizzare questo:

$(document).ready(function(){
    $("body").on("focus","input[type=text].number,.NUMBER",function(e){
        $(e.target).data('oldValue',$(e.target).val());
    }); 
    $("body").on("keypress","input[type=text].number,.NUMBER",function(e){
        e.target.oldvalue = e.target.value;
        number(e);
    }); 
    $("body").on("change","input[type=text].number,.NUMBER",function(e){
        var t = e.target
        var min = $(t).attr("min");
        var max = $(t).attr("max");
        var val = parseInt($(t).val());         
        if( val<min || max<val)
            {
                alert("Error!");
                $(t).val($(t).data('oldValue'));
            }
    }); 
});

La mia soluzione per una migliore esperienza utente:

  

HTML

<input type="tel">
  

jQuery

$('[type=tel]').on('change', function(e) {
  $(e.target).val($(e.target).val().replace(/[^\d\.]/g, ''))
})
$('[type=tel]').on('keypress', function(e) {
  keys = ['0','1','2','3','4','5','6','7','8','9','.']
  return keys.indexOf(event.key) > -1
})

Dettagli:

Prima di tutto, tipi di input :

numero mostra le frecce su / giù che riducono lo spazio di input effettivo, li trovo brutti e sono utili solo se il numero rappresenta una quantità (cose come telefoni, prefissi, ID ... don ' ne ho bisogno) tel fornisce convalide del numero simili per browser senza frecce

L'uso di [numero / tel] aiuta anche a mostrare la tastiera numerica sui dispositivi mobili.

Per la convalida JS ho finito per aver bisogno di 2 funzioni, una per l'input dell'utente normale (pressione dei tasti) e l'altra per una correzione copia + incolla (modifica), altre combinazioni mi darebbero un'esperienza terribile per l'utente.

Uso il più affidabile KeyboardEvent.key anziché ora deprecato KeyboardEvent.charCode

E a seconda del supporto del tuo browser puoi prendere in considerazione l'utilizzo di Array.prototype.includes () invece del povero Array.prototype.indexOf () (per risultati true / false)

Un modo semplice per risolvere questo problema è l'implementazione di una funzione jQuery per convalidare con regex i caratteri digitati nella casella di testo, ad esempio:

Il tuo codice html:

<input class="integerInput" type="text">

E la funzione js usa jQuery

$(function() {
    $('.integerInput').on('input', function() {
      this.value = this.value
        .replace(/[^\d]/g, '');// numbers and decimals only

    });
});

$(function() {
        $('.integerInput').on('input', function() {
          this.value = this.value
            .replace(/[^\d]/g, '');// numbers and decimals only
            
        });
    });
<script
			  src="https://code.jquery.com/jquery-2.2.4.min.js"
			  integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="
			  crossorigin="anonymous">
</script>

<input type="text" class="integerInput"/>


		

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top