Muy interesante y didactico. Sigan adelante felicitaciones!!!
13/3/06
Por: Miguel Hernández MontanoEl programa no funciona cuando coloco cero (0) antes de cualquier número, por ejemplo: 012, no me devuelve 12 como debería de ser lo correcto, sino otra cantidad.
no devuelve nada al ir a validar :S :S
Por fin!!!
Llevaba unas cuantas horas buscando como validar campo numérico y ha sido la única página que me ha servido de utilidad!!
Felicidades desarrolloweb!!
Que pasa si validas este campo: 33b
Parece que pincha como loco
Ante todo muchas gracias por todos los articulos k me han sido de mucha ayuda. Tengo un problema con este scripts y muchos con javascript por ejemplo la funcion parseInt() ningun navegador me lo reconoce ni me tiran error de js tampoco, el javascript lo tengo habilitado, asi que no se trata de eso. la verdad no se que pueda ser. y tampoco se trata de la version porqeu he probado distintas y siempre ocurre lo mismo, pero accedi desde otros lugares y el script que esta aca anda. Si tienen alguna idea de lo que pueda ser por favor mandenme una respuesta. Muchas gracias...
Fabian tiene razón, si se pone un número 123kkk, la función parseInt nos va a devolver 123, pero es no es lo que queríamos hacer. A mí me funciona el siguiente código:
if(!eregi("^[0-9]{4,}$",$cadena)){
/*la variable tiene algún valor no númerico, poner aquí las acciones para ese caso*/
}else{
/*La variable es un número*/
}
lo que hace básicamente ese código es:
-Revisar que la variable $cadena tenga dígitos entre 0 y 9:
[0-9]
y que tenga como mínimo 4 dígitos (me sirve si quiero revisar por ej. un número de teléfono):
{4,}
Para más información sobre la función eregi, le sugiero revisar: http://weblogtoolscollection.com/regex/regex.php
excelente compilación.
----Actualización!-----
El código que puse es para php (jeje, pensé que el artículo era de php :P) así que si lo usan en javascript no les va a funcionar, pero existe un método análago en javascript, que es el siguiente:
if (miCadena.match(/^d+$/)){
/*la variable miCadena es numérico*/
}else{
/*no es númerico*/
}
El regex:
/^d+$/
Filtra cadenas que consistan únicamente de dígitos.
Vean esa página para más información:
http://www.regular-expressions.info/javascript.html
var defaultEmptyOK = false
var checkNiceness = true;
var digits = "0123456789";
var lowercaseLetters = "abcdefghijklmnopqrstuvwxyzáéíóúñü"
var uppercaseLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZÁÉÍÓÚÑ"
var whitespace = "
";
var phoneChars = "()-+ ";
var mMessage = "Error: no puede dejar este espacio vacio"
var pPrompt = "Error: ";
var pAlphanumeric = "ingrese un texto que contenga solo letras y/o numeros";
var pAlphabetic = "ingrese un texto que contenga solo letras";
var pInteger = "ingrese un numero entero";
var pNumber = "ingrese un numero";
var pPhoneNumber = "ingrese un número de teléfono";
var pEmail = "ingrese una dirección de correo electrónico válida";
var pName = "ingrese un texto que contenga solo letras, numeros o espacios";
var pNice = "no puede utilizar comillas aqui";
function makeArray(n) {
for (var i = 1; i <= n; i++) {
this[i] = 0
}
return this
}
function isEmpty(s)
{ return ((s == null) || (s.length == 0))
}
function isWhitespace (s)
{ var i;
if (isEmpty(s)) return true;
for (i = 0; i < s.length; i++)
{
var c = s.charAt(i);
// si el caracter en que estoy no aparece en whitespace,
// entonces retornar falso
if (whitespace.indexOf(c) == -1) return false;
}
return true;
}
function stripCharsInBag (s, bag)
{ var i;
var returnString = "";
// Buscar por el string, si el caracter no esta en "bag",
// agregarlo a returnString
for (i = 0; i < s.length; i++)
{ var c = s.charAt(i);
if (bag.indexOf(c) == -1) returnString += c;
}
return returnString;
}
function stripCharsNotInBag (s, bag)
{ var i;
var returnString = "";
for (i = 0; i < s.length; i++)
{
var c = s.charAt(i);
if (bag.indexOf(c) != -1) returnString += c;
}
return returnString;
}
function stripWhitespace (s)
{ return stripCharsInBag (s, whitespace)
}
function charInString (c, s)
{ for (i = 0; i < s.length; i++)
{ if (s.charAt(i) == c) return true;
}
return false
}
function stripInitialWhitespace (s)
{ var i = 0;
while ((i < s.length) && charInString (s.charAt(i), whitespace))
i++;
return s.substring (i, s.length);
}
function isLetter (c)
{
return( ( uppercaseLetters.indexOf( c ) != -1 ) ||
( lowercaseLetters.indexOf( c ) != -1 ) )
}
function isDigit (c)
{ return ((c >= "0") && (c <= "9"))
}
function isLetterOrDigit (c)
{ return (isLetter(c) || isDigit(c))
}
function isInteger (s)
{ var i;
if (isEmpty(s))
if (isInteger.arguments.length == 1) return defaultEmptyOK;
else return (isInteger.arguments[1] == true);
for (i = 0; i < s.length; i++)
{
var c = s.charAt(i);
if( i != 0 ) {
if (!isDigit(c)) return false;
} else {
if (!isDigit(c) && (c != "-") || (c == "+")) return false;
}
}
return true;
}
function isNumber (s)
{ var i;
var dotAppeared;
dotAppeared = false;
if (isEmpty(s))
if (isNumber.arguments.length == 1) return defaultEmptyOK;
else return (isNumber.arguments[1] == true);
for (i = 0; i < s.length; i++)
{
var c = s.charAt(i);
if( i != 0 ) {
if ( c == "." ) {
if( !dotAppeared )
dotAppeared = true;
else
return false;
} else
if (!isDigit(c)) return false;
} else {
if ( c == "." ) {
if( !dotAppeared )
dotAppeared = true;
else
return false;
} else
if (!isDigit(c) && (c != "-") || (c == "+")) return false;
}
}
return true;
}
function isAlphabetic (s)
{ var i;
if (isEmpty(s))
if (isAlphabetic.arguments.length == 1) return defaultEmptyOK;
else return (isAlphabetic.arguments[1] == true);
for (i = 0; i < s.length; i++)
{
// Check that current character is letter.
var c = s.charAt(i);
if (!isLetter(c))
return false;
}
return true;
}
function isAlphanumeric (s)
{ var i;
if (isEmpty(s))
if (isAlphanumeric.arguments.length == 1) return defaultEmptyOK;
else return (isAlphanumeric.arguments[1] == true);
for (i = 0; i < s.length; i++)
{
var c = s.charAt(i);
if (! (isLetter(c) || isDigit(c) ) )
return false;
}
return true;
}
function isName (s)
{
if (isEmpty(s))
if (isName.arguments.length == 1) return defaultEmptyOK;
else return (isAlphanumeric.arguments[1] == true);
return( isAlphanumeric( stripCharsInBag( s, whitespace ) ) );
}
function isPhoneNumber (s)
{ var modString;
if (isEmpty(s))
if (isPhoneNumber.arguments.length == 1) return defaultEmptyOK;
else return (isPhoneNumber.arguments[1] == true);
modString = stripCharsInBag( s, phoneChars );
return (isInteger(modString))
}
function isEmail (s)
{
if (isEmpty(s))
if (isEmail.arguments.length == 1) return defaultEmptyOK;
else return (isEmail.arguments[1] == true);
if (isWhitespace(s)) return false;
var i = 1;
var sLength = s.length;
while ((i < sLength) && (s.charAt(i) != "@"))
{ i++
}
if ((i >= sLength) || (s.charAt(i) != "@")) return false;
else i += 2;
while ((i < sLength) && (s.charAt(i) != "."))
{ i++
}
if ((i >= sLength - 1) || (s.charAt(i) != ".")) return false;
else return true;
}
function isNice(s)
{
var i = 1;
var sLength = s.length;
var b = 1;
while(i<sLength) {
if( (s.charAt(i) == """) || (s.charAt(i) == "'" ) ) b = 0;
i++;
}
return b;
}
function statBar (s)
{ window.status = s
}
function warnEmpty (theField)
{ theField.focus()
alert(mMessage)
statBar(mMessage)
return false
}
function warnInvalid (theField, s)
{ theField.focus()
theField.select()
alert(s)
statBar(pPrompt + s)
return false
}
function checkField (theField, theFunction, emptyOK, s)
{
var msg;
if (checkField.arguments.length < 3) emptyOK = defaultEmptyOK;
if (checkField.arguments.length == 4) {
msg = s;
} else {
if( theFunction == isAlphabetic ) msg = pAlphabetic;
if( theFunction == isAlphanumeric ) msg = pAlphanumeric;
if( theFunction == isInteger ) msg = pInteger;
if( theFunction == isNumber ) msg = pNumber;
if( theFunction == isEmail ) msg = pEmail;
if( theFunction == isPhoneNumber ) msg = pPhoneNumber;
if( theFunction == isName ) msg = pName;
}
if ((emptyOK == true) && (isEmpty(theField.value))) return true;
if ((emptyOK == false) && (isEmpty(theField.value)))
return warnEmpty(theField);
if ( checkNiceness && !isNice(theField.value))
return warnInvalid(theField, pNice);
if (theFunction(theField.value) == true)
return true;
else
return warnInvalid(theField,msg);
}
02/7/09
Muy buenoPor: Rafael MunetonMe parece excelente el articulo, es lo que yo andaba buscando.
Ahora lo voy a aplicar dentro de mis scripts de Perl, espero no tener problemas.
Muchas gracias.