Javascript - Validating Numeric Field (popup)

Asked

Viewed 2,363 times

3

I have a screen that has 4 inputs. The value of these inputs is being saved in my database. But I need to figure out how I do to validate these fields being only numerical fields?

I tried a code found on the web, but it didn’t go very well.

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>
  • 1

    The onblur event is for when you take the focus off the field and you’re putting it on the button, you’re also passing the value of the button and not the inputs. One way to work is to place the checkNumber(this.value) function in the onblur event of each input.

  • You mean like Diego? <label class="label">Humidity: </label> <input type="text" id="Humidity" size="50" value="" onblur="checkNumber(this.value);"> <br>

  • In addition to what @Diegoschmidt said, I think you could create a variable regexp var regra =new RegExp("/^[0-9]+$/") and when validating regexp use regra.test(valor)

  • Right, just like that. Before you were passing the value of the button and its input.

  • But if you are using Html5 why not use input type="number"?

  • @Leonardobonetti: I didn’t understand very well..

  • @Everson: I have no idea.. As I said, I know very little web language, so I came to you myself..

  • @cardealt I described in my reply how is the input syntax of type number (number ) and a solution with javascript to restrict the field to numbers only.

Show 3 more comments

4 answers

1

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

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

An example working the way your question:

<!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 containing a certain 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, age for example, 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 of how to enable another field if a given field is valid, I used the disabled property of html:

<!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>
  • Perfect Diego!! Thank you so much!!! :)

  • You did, but can I ask you a question? And if I wanted while the input is filled with a character other than number, not allow you to jump to the next input, as you would do?

  • I edited the answer.

  • Thank you very much!!

0

You can restrict so that the user does not enter any other character than numbers through a mask for each field. With the mask you can define how many numerical 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>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.0/jquery.mask.js"></script>

Número 1 <input type="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 HTML5 only, use the type field number.

Número <input type="number" name="numero">

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 function Number tries to convert the value to numeric, and only in case of failure returns NaN (fixed value to mean "invalid number"). The second function checks whether the given value is an NaN.

Advantages of using the function isNaN together with the Number:

  • Very fast, as they are implemented in the browser;
  • Less code to keep;
  • The code you found on the Internet does not consider non-integer numbers (e.g.: 2.1) as numbers. The above combination considers;
  • Using basic Javascript functions is an agnostic way for frameworks to solve problems. And you can validate values that didn’t necessarily come from the form, if one day you have to validate data from other sources.

You just need a more elaborate function if you want to force a format number, but there’s another problem.

  • I guess I didn’t quite understand :/

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)">
  • Thank you so much for the return :))

Browser other questions tagged

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