0

I need a regular expression for a comma separated values, that accept positive/negative integer and also float numbers.

Ej: 3,45,2.5,12,-20

How do I get it? Thanks

I need to implement a function that adds values and returns the result, and it detects a pattern of incorrect entry such numbers separated by hyphens

Ej: 3,45,2.5,12,-20 (Correct)

Ej: 3-45-2.5-12-20 (Incorrect)

but I do not get it, the code I have:

<html>
<head>
<script type="text/javascript">
function validar()
{
var patron = /^(-?\d*\.?\d*,?)+$/;                         
var numeros = document.getElementById("numeros").value;

if (!patron.test(numeros)) 
{        
    alert("Introduzca los números que desee sumar separados por comas, Ej: 3,3.25,-1");                      
}
else 
{
    suma();     
}
} 

function suma()
{
var entrada = document.getElementById("numeros").value;
var numeros = entrada.split(",");
var suma = 0;

for(var i = 0; i < numeros.length; i++)
    {
        suma += parseFloat(numeros[i]);
    }
document.getElementById("resultado").value = suma;
}    
</script>
</head>
<body>
Números: <input type="text" id="numeros" size="30">
Resultado: <input type="text" id="resultado" size="20">
<input type="button" value="SUMAR" onClick="validar()">
</body>
</html>
0

1 Answer 1

0

Basicly a duplicate of this and this.

"3,45,2.5,12,-20".split(",").every( 
    function(x) { return /^-?\d*\.?\d*$/.test(x); }
);

Or as single regex

/^(-?\d*\.?\d*)(,-?\d*\.?\d*)*$/.test("3,45,2.5,12,-20")

After a bit of refactoring you will get

<html>
<head>
 <title>JS Números</title>
</head>

<body>
Números: <input type="text" id="numeros" size="30">
Resultado: <input type="text" id="resultado" size="20">
<input type="button" value="SUMAR" onClick="suma()">

<script type="text/javascript">
var numberElement = document.getElementById("numeros");
var resultElement = document.getElementById("resultado");
var numberPattern = /^(-?\d*\.?\d*)(,-?\d*\.?\d*)*$/;

function suma() {
    var numberString = numberElement.value;
    if (numberPattern.test(numberString)) {
        var sum = numberString.split(",").reduce(function(m,v) { return m + parseFloat(v); }, 0);
        resultElement.value = sum;
    } else {
        alert("Introduzca los números que desee sumar separados por comas, Ej: 3,3.25,-1");
        resultElement.value = "";
    }
}    
</script>
</body>
</html>
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.