Javascript - Validating numeric field (popup)

3

I have a screen that has 4 inputs. The value of these inputs is being saved in my database. But do I need to find out how I can validate these fields as just numeric fields?

I tried a code found on the web, but it did not work.

function checkNumber(valor) {
        var regra = /^[0-9]+$/;
        if (valor.match(regra)) {
            alert("Numero: "+valor);
        }else{
            alert("Permitido somente números);
        }
    };


 <button class="botao1" onblur="checkNumber(this.value);" onclick="publish(JSON.stringify(pl),topic, 2);">3. Publish</button>
    
asked by anonymous 13.06.2017 / 18:50

4 answers

1

The event onblur is for when you take the focus of the field and you are putting it on the button, you are also passing the value of the button, not the inputs.

One way to work is to put the checkNumber (this.value) function in the onblur event of each input.

An example working the way your question is:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>Título da pagina</title>
        <script>
            function checkNumber(value) {
                if (value.trim() !== "") {
                    var regra = /^[0-9]+$/;
                    if (value.match(regra)) {
                        alert("Numero: " + value);
                    } 
                    else {
                        alert("Permitido somente números");
                    }
                }
            }
        </script>
    </head>

    <body>
        <input type="text" name="idade" id="idade" onblur="checkNumber(this.value)"/>
    </body>
</html>

An example validating several fields where they contain a given class:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>Título da pagina</title>      
        <script>
            function validaCamposSomenteNumero() {
                var inputs = document.getElementsByClassName("somente-numero");
                for (var i = 0; i < inputs.length; ++i) {
                    var input = inputs[i];  
                    if (input.value !== "") {
                        if (isNaN(input.value)) {
                            alert("Preencha somente número!");
                            return;
                        }
                    }               
                }
            }
        </script>
    </head>

    <body>
        <input type="text" name="idade" id="idade" class="somente-numero"/>
        <input type="text" name="idade2" id="idade2" class="somente-numero"/>
        <input type="button" value="Cadastrar" onclick="validaCamposSomenteNumero()"/>
    </body>
</html>

An example where you want a field to have exactly 4 numbers, for example age using HTML5.

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>Título da pagina</title>      
    </head>

    <body>
        <form action="" method="post">
            <input type="text" name="idade" id="idade" pattern="^[0-9]{4}$" title="Preencha a idade corretamente."/>
            <input type="submit">
        </form>
    </body>
</html>

Allowing a field to contain only numbers using HTML5:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>Título da pagina</title>
    </head>

    <body>
        <input type="number" name="idade" id="idade"/>
    </body>
</html>

Answering your question about how to enable another field if a given field is valid, I used the html disabled property:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>Título da pagina</title>  
        <script>
            function validaCampo(value) {
                if (value.trim() !== "") {
                    var campoParaHabilitar = document.getElementById("campo2");
                    if (!isNaN(value.trim())) {
                        campoParaHabilitar.disabled = false;
                    }
                    else {
                        campoParaHabilitar.disabled = true;
                    }

                }       
            }
        </script>
    </head>

    <body>
        <input type="text" name="campo1" id="campo1" onblur="validaCampo(this.value)"/>
        <input type="text" name="campo2" id="campo2" disabled/>
    </body>
</html>
    
13.06.2017 / 19:27
0

Javascript has very simple native functions that can help you in this case. Try it on the console:

var foo;
// preencha foo
isNaN(Number(foo)); //retornará verdadeiro se foo não for uma representação de um número

How it works: The Number function tries to convert the value to numeric, and only on failure it returns NaN " (fixed value to mean "invalid number"). The second function checks whether the value reported to it is NaN .

Advantages of using isNaN together with Number :

  • Very fast because they are implemented in the browser;
  • Less code to keep;
  • The code that you found on the internet does not consider non-integers (e.g .: 2.1) as numbers. The above combination considers;
  • Using basic JavaScript functions is an agnostic way to problem solving frameworks. And you can validate values that did not necessarily come from the form if you ever have to validate data from other sources.

You only need a more verbose function if you want to force a number format , but that's another problem.

    
13.06.2017 / 19:04
0

You can restrict the user from typing any characters other than numbers through a mask for each field. With the mask you can define how many numeric digits each field should have. In the example below the fields are restricted to 4, 5, 6 and 7 digits, respectively.

jQuery(function($){
   $("#numero1").mask("9999");
   
   $("#numero2").mask("99999");
   
   $("#numero3").mask("999999");
   
   $("#numero4").mask("9999999");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><scripttype="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.0/jquery.mask.js"></script>Número1<inputtype="text" id="numero1" name="numero" maxlength="4" placeholder="4 dígitos numéricos"/><br><br>
Número 2 <input type="text" id="numero2" name="numero" maxlength="5" placeholder="5 dígitos numéricos"/><br><br>
Número 3 <input type="text" id="numero3" name="numero" maxlength="6" placeholder="6 dígitos numéricos"/><br><br>
Número 4 <input type="text" id="numero4" name="numero" maxlength="7" placeholder="7 dígitos numéricos"/><br><br>

Or, if you prefer to use only HTML5, use the field of type number .

Número <input type="number" name="numero">
    
13.06.2017 / 19:03
0

Validation only numbers with a dot separating decimal places. DEMO

SCRIPT

function checkfloat(e,field){
  if (!(((e.keyCode>=48)&&(e.keyCode<=57))||(e.keyCode==46)))
  {
     alert("Somente numeros inteiros ou fracionários separado por ponto!");
     e.keyCode=0;                   
  }

  if (e.keyCode==46)
  {
     var patt1=new RegExp("\.");        
     var ch =patt1.exec(field); 

     if(ch==".")
     {
         alert("Mais que um ponto decimal não é permitido");
         e.keyCode=0;
     }                     
  }      
} 

HTML

<input type="text" id="a" size="5" onkeypress="checkfloat(event, this.value)">
<input type="text" id="b" size="5" onkeypress="checkfloat(event, this.value)">
<input type="text" id="c" size="5" onkeypress="checkfloat(event, this.value)">
<input type="text" id="d" size="5" onkeypress="checkfloat(event, this.value)">
    
13.06.2017 / 20:08