How to validate numeric fields in javascript?

Asked

Viewed 1,174 times

1

I need to assemble a code in HTML x Javascript, with two fields for typing numerical values and a button calculate. By pressing the calculate button, the application should emit on the screen the result of the sum of the two entered values. I’m not being able to validate in javascript.

  • If possible click on [Edit] and post your code.

  • Probably what you want is not validation but to convert the values to int or float.

  • and how do I do that

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>

Thus, 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 the strings for numbers, I used the constructor Number().
But you could also have used the methods parseInt() or parseFloat().

  • was really worth getting

  • null + null is not zero

1

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

  • I liked the Sr. Burro :D

  • I removed that answer from the goats. I thought it was not worth it because the problem should be essentially in PHP: https://answall.com/q/291375/8063

0

As stated in the reply of @Luiz Felipe, it is necessary to convert the value of the fields to numeric type. In the case here I used parseFloat().

Also, you can use a short-circuit evaluator to convert some the field that was left empty into 0, to avoid the 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>

  • thank you very much.

  • very good! I am new in this world of rsrs programming

  • @Leocaracciolo It’s just to avoid Nan.

  • @Leocaracciolo I agree with you. But as I put in the answer, it is only to convert the null into zero, it was only a suggestion.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.