How to validate numeric fields in javascript?

1

I need to assemble a code in HTML x Javascript, with two fields for entering numeric values and a button for calculate. When you press the calculate button, the application should output the result of the sum of the two values entered on the screen. I'm not able to do validation in javascript.

    
asked by anonymous 14.04.2018 / 20:14

3 answers

1

By default, all input values come in as string , see:

document.getElementById('check').addEventListener('click', function() {
  var field = document.getElementById('input');
  
  // Mostra o valor e em seguida o tipo:
  alert(field.value);
  alert(typeof field.value);
});
<input id="input" type="number" value="44" />
<button id="check">Clique</button>

In this way, we need to transform the value of the field into a number.

var numberInString = '20';
var number = Number(numberInString);

console.log(typeof number); // number

So, I think what you need is:

document.getElementById('calc-sum').addEventListener('click', function() {
  var num1 = document.getElementById('num-1');
  var num2 = document.getElementById('num-2');
  
  // Transformar os valores em números:
  num1 = Number(num1.value);
  num2 = Number(num2.value);
  
  // Calcular a soma:
  var sum = num1 + num2;
  
  // Mostrar a soma:
  document.getElementById('sum').innerText = 'A soma é: ' + sum;
});
<label>Valor 01: </label>
<input id="num-1" type="number" />
<br>
<label>Valor 01: </label>
<input id="num-2" type="number" />
<br><br>
<input type="button" id="calc-sum" value="Calcular soma">
<br><br>
<div id="sum"></div>

Note:

To convert string s to numbers, I used the Number() constructor. But you could also have used the methods parseInt() or parseFloat() .

    
14.04.2018 / 20:41
1

Assuming that the result of the sum of (vazio + vazio) or (nulo + nulo) or ( e + e ) or ( espaços + espaços ) is not zero, we have

    function validarNum() {
        var x, texto;

        // Obtem os valores dos campos de entrada com id = "numero"
        x = document.getElementById("numero1").value;
        y = document.getElementById("numero2").value;
        
        z = (parseFloat(x)+parseFloat(y));

        if (isNaN(z)) {
            texto = "Sr. Burro, preencha os campos corretamente";
        } else {
            texto = (parseFloat(x)+parseFloat(y));
        }
        console.log(texto);
    }
    <input id="numero1">
    
    <input id="numero2">

    <button type="button" onclick="validarNum()">Somar</button>
    
14.04.2018 / 20:48
0

As stated in @Luiz Felipe response, you must convert the value of the fields to numeric type. In this case I used parseFloat() .

Additionally, you can use a short-circuit evaluator for convert any field that was left empty to 0 , to avoid NaN .

Example:

function calcular(){
   var val1 = parseFloat(document.body.querySelector("#valor1").value) || 0;
   var val2 = parseFloat(document.body.querySelector("#valor2").value) || 0;
                                                                       // ↑
       // caso o campo esteja vazio ou não seja um número, o valor assume 0
   console.log(val1+val2);
}
Insira os dois valores (deixe um em branco para testar a soma):
<br>
<input id="valor1">
<input id="valor2">
<br>
<button type="button" onclick="calcular()">Calcular</button>
    
14.04.2018 / 20:56