2010-03-09 13 views
22

Ho un problema semplice - Vorrei controllare un campo per vedere se è un numero intero se non è vuoto. Non sto usando alcun plugin aggiuntivo, solo jQuery. Il mio codice è il seguente:jquery: convalidare che il campo di testo è numerico

if($('#Field').val() != "") 
{ 
    if($('#Field').val().match('^(0|[1-9][0-9]*)$')) 
    { 
     errors+= "Field must be numeric.<br/>"; 
     success = false; 
    } 
} 

... Non sembra funzionare. Dove sto andando male?

L'errore che ricevo è val() is not an object.

AGGIORNAMENTO: ho scoperto che il vero problema era che avevo il mio nome dell'elemento impostato e non l'ID.

+1

Ti manca una citazione di chiusura sulla prima riga - è che solo un errore di battitura? –

+0

quando dici "numerico", intendi qualsiasi tipo di numero (float e whatnot) o intendi un numero intero? – karim79

+1

http://stackoverflow.com/questions/18082/validate-numbers-in-javascript-isnumeric –

risposta

22

Questo dovrebbe funzionare. Vorrei trim the whitespace dal campo di ingresso prima di tutto:

if($('#Field').val() != "") { 
    var value = $('#Field').val().replace(/^\s\s*/, '').replace(/\s\s*$/, ''); 
    var intRegex = /^\d+$/; 
    if(!intRegex.test(value)) { 
     errors += "Field must be numeric.<br/>"; 
     success = false; 
    } 
} else { 
    errors += "Field is blank.</br />"; 
    success = false; 
} 
+0

Ottengo val() non è un oggetto con questo pure. –

+0

@George Johnston - perché l'avevo appena digitato direttamente nel browser contro il mio giudizio migliore, ed è stato completamente interrotto. Prova ora, se vuoi. – karim79

4

So che non c'è bisogno di aggiungere un plugin per questo. Ma questo può essere utile se stai facendo tante cose con i numeri. Quindi verifica il plugin this almeno per il punto di vista della conoscenza. La risposta di karim79 per il riposo è super cool.

<!DOCTYPE html> 
    <html> 
    <head> 
     <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script> 
     <script type="text/javascript" src="jquery.numeric.js"></script> 
    </head> 
    <body> 
     <form> 
      Numbers only: 
      <input class="numeric" type="text" /> 
      Integers only: 
      <input class="integer" type="text" /> 
      No negative values: 
      <input class="positive" type="text" /> 
      No negative values (integer only): 
      <input class="positive-integer" type="text" /> 
      <a href="#" id="remove">Remove numeric</a> 
     </form> 
     <script type="text/javascript"> 
     $(".numeric").numeric(); 
     $(".integer").numeric(false, function() { alert("Integers only"); this.value = ""; this.focus(); }); 
     $(".positive").numeric({ negative: false }, function() { alert("No negative values"); this.value = ""; this.focus(); }); 
     $(".positive-integer").numeric({ decimal: false, negative: false }, function() { alert("Positive integers only"); this.value = ""; this.focus(); }); 
     $("#remove").click(
      function(e) 
      { 
       e.preventDefault(); 
       $(".numeric,.integer,.positive").removeNumeric(); 
      } 
     ); 
     </script> 
    </body> 
    </html> 
26

Regex non è necessario, né i plugin

if (isNaN($('#Field').val()/1) == false) { 
    your code here 
} 
+1

+1 cose carine !!! – ggzone

3

io non sono certo quando questo è stato implementato, ma al momento è possibile utilizzare http://api.jquery.com/jQuery.isNumeric/

if($('#Field').val() != "") 
{ 
    if($.isNumeric($('#Field').val()) { 
     errors+= "Field must be numeric.<br/>"; 
     success = false; 
    } 
} 
0

Tutti convalida Basic utilizzando per classe

$('.IsInteger,.IsDecimal').focus(function (e) { 
    if (this.value == "0") { 
     this.value = ""; 
    } 
}); 
$('.IsInteger,.IsDecimal').blur(function (e) { 
    if (this.value == "") { 
     this.value = "0"; 
    } 
}); 

$('.IsInteger').keypress(function (e) { 
    var charCode = (e.which) ? e.which : e.keyCode; 
    if (charCode > 31 
    && (charCode < 48 || charCode > 57)) 
     return false; 
}); 
$('.IsDecimal').keypress(function (e) { 
    var charCode = (e.which) ? e.which : e.keyCode; 
    if (this.value.indexOf(".") > 0) { 
     if (charCode == 46) { 
      return false; 
     } 
    } 
    if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57)) 
     return false; 
}); 
$('.IsSpecialChar').keypress(function (e) { 
    if (e.keyCode != 8 && e.keyCode != 46 && e.keyCode != 37 && e.keyCode != 38 && e.keyCode != 39 && e.keyCode != 40) 
     return false; 
    else 
     return true; 
}); 
$('.IsMaxLength').keypress(function (e) { 
    var length = $(this).attr("maxlength"); 
    return (this.value.length <= length); 
}); 

$('.IsPhoneNumber').keyup(function (e) { 
    var numbers = this.value.replace(/\D/g, ''), 
    char = { 0: '(', 3: ') ', 6: ' - ' }; 
    this.value = ''; 
    for (var i = 0; i < numbers.length; i++) { 
     this.value += (char[i] || '') + numbers[i]; 
    } 
}); 
$('.IsEmail').blur(function (e) { 
    var flag = false; 
    var email = this.value; 
    if (email.length > 0) { 
     var regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/; 
     flag = regex.test(email); 
    } 
    if (!flag) 
     this.value = ""; 
}); 

Esempio: -

nome di classe appena messo in ingresso

0

Non avete bisogno di espressioni regolari per questo. Utilizzare la funzione javascript isNAN().

La funzione isNaN() determina se un valore è un numero non valido (Not-a-Number). Questa funzione restituisce true se il valore è NaN e false in caso contrario.

if (isNaN($('#Field').val()) == false) { 

    //it's a number 
} 
Problemi correlati