2010-03-09 25 views
22

Tengo un problema simple: me gustaría verificar un campo para ver si es un número entero si no está en blanco. No estoy usando ningún complemento adicional, solo jQuery. Mi código es el siguiente:jquery: validar que el campo de texto es numérico

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

... Parece que no funciona. ¿Dónde estoy equivocado?

El error que recibo es val() is not an object.

ACTUALIZACIÓN: Resultó que el problema real era que tenía el nombre de mi elemento establecido y no el Id.

+1

Usted se echa en falta una cotización de cierre en la primera línea - es que sólo un error tipográfico? –

+0

cuando dices numérico, ¿te refieres a cualquier tipo de número (flotantes y demás) o te refieres a un número entero? – karim79

+1

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

Respuesta

22

Esto debería funcionar. Lo haría trim the whitespace del campo de entrada en primer lugar:

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

Obtengo val() no es un objeto con esto también. –

+0

@George Johnston - porque acababa de tipearlo directamente en el navegador en contra de mi mejor juicio, y estaba completamente borracho. Pruébalo ahora, si quieres. – karim79

4

Sé que no hay necesidad de añadir un plugin para esto. Pero esto puede ser útil si estás haciendo muchas cosas con los números. Por lo tanto, compruebe el complemento this al menos para el punto de vista del conocimiento. Rest karim79 la respuesta es súper genial.

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

expresión regular no es necesario, ni es plugins

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

+1 cosas agradables! – ggzone

3

no estoy seguro cuando este se puso en práctica, pero en la actualidad se puede utilizar http://api.jquery.com/jQuery.isNumeric/

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

Todo validación básica usando por clase

$('.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 = ""; 
}); 

Ejemplo: -

nombre de la clase sólo hay que poner en la entrada

0

No es necesario expresiones regulares para éste. Utilice la función de Javascript isNAN().

La función isNaN() determina si un valor es un número ilegal (Not-a-Number). Esta función devuelve verdadero si el valor es NaN y es falso si no es así.

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

    //it's a number 
} 
Cuestiones relacionadas