javascript numeral validation

Asked

Viewed 1,184 times

0

I am trying to validate a form. the user can only instill numeral values. I did it this way but it’s not working

function ValidateContactForm()
{
    var year = document.ContactForm.year;

  if (year.value == "")
{
    isNaN( document.myForm.edition.value)
    window.alert("Please enter year.");
    year.focus();
    return false;
}  
}

code in HTML

<body>
        <?php include 'addDataAdmin.php';?>
        <form name="ContactForm" action="addDataAdmin.php" method="POST" enctype="multipart/form-data" autocomplete="off" onsubmit="return ValidateContactForm();">
            ISBN:<input type="text" name="ISBN">
            Author's Name:<input type="text" name="Authorsname">
            Title:<input type="text" name="Title">
            Edition:<input type="number" name="edition">
            Year:<input type="number" name="year">

            Category:
            <select name="category" size="1">
                <option value="computing">Computing</option>
                <option value="Romance">Romance</option>
                <option value="Fiction">Fiction</option>
                <option value="Non-Fiction">Non-Fiction</option>
            </select>
            <br />

            Publisher:<input type="text" name="publisher">
            Quantity-in-stock:<input type="number" name="quantityinstock">
            Price:<input type="number" name="price">
            <input type="file" name="fileToUpload" id="fileToUpload">
            <input type="submit" value="Upload Image" name="submit" formaction="/upload.php">
            <input type="submit" value="Send" name="send">
            <input type="reset" value="Clear">
        </form>
    </body>
</html>
  • You can put your HTML?

  • I reissued the answer to a function only validate the numeric fields

  • put Alert in response

  • Thanks Leo, I tested and it didn’t work after I saw that it is missing only one { in your code but otherwise all right!

3 answers

2


SCRIPT

    function SomenteNumero(e){
      var tecla=(window.event)?event.keyCode:e.which;   
        if((tecla>47 && tecla<58)) return true;
        else{
           if (tecla==8 || tecla==0) return true;
        else  
           alert ( "Este campo aceita apenas números.");
           return false;
        }
    }

HTML

In inputs that must accept only numbers put:

onkeypress='Return Somentenumero(Event)'

   <body>
        <?php include 'addDataAdmin.php';?>
        <form name="ContactForm" action="#" method="POST" enctype="multipart/form-data" autocomplete="off">
            ISBN:<input type="text" name="ISBN">
            Author's Name:<input type="text" name="Authorsname">
            Title:<input type="text" name="Title">
            Edition:<input type="number" name="edition" onkeypress='return SomenteNumero(event)'>
            Year:<input type="number" name="year" onkeypress='return SomenteNumero(event)'>

            Category:
            <select name="category" size="1">
                <option value="computing">Computing</option>
                <option value="Romance">Romance</option>
                <option value="Fiction">Fiction</option>
                <option value="Non-Fiction">Non-Fiction</option>
            </select>
            <br />

            Publisher:<input type="text" name="publisher">
            Quantity-in-stock:<input type="number" name="quantityinstock" onkeypress='return SomenteNumero(event)'>
            Price:<input type="number" name="price">
            <input type="file" name="fileToUpload" id="fileToUpload">
            <input type="submit" value="Upload Image" name="submit" formaction="/upload.php">
            <input type="submit" value="Send" name="send">
            <input type="reset" value="Clear">
        </form>
    </body>

Demonstration

function SomenteNumero(e){
    var tecla=(window.event)?event.keyCode:e.which;   
    if((tecla>47 && tecla<58)) return true;
    else{
    	if (tecla==8 || tecla==0) return true;
	else  
	alert ( "Este campo aceita apenas números.");
	return false;
    }
}
	
<input type="text" class="verificar" name="nome" size="2" onkeypress="return SomenteNumero(event)">

  • hi Leo. I edited and put my HTML code. it will not be more effective to do otherwise than to create a new function?

  • hi Leo is working, the problem is that I have two input that will make use of the function someNumero, the problem is that I need to have an Alert window for each one, and at this point with the function only Number is not working

  • I edited the answer to meet your conditions

1

You don’t need Javascript for this, just go to your form and change the input to a number(HTML5 type):

Example:

 <input type="number" size="6" name="age" min="18" max="99" value="21" required />
  • I think it’s worth an addendum that is HTML5 :)

  • 1

    Oops! I’ll edit it

  • Hi Lucas I’ve been trying and it actually helps to put this kind of input. but the problem is that this input allows you to put number one to one by a few arrows in the corner. but I have a text box where I have to insert price of a product there this input that Voce suggested no longer does what I want, or even to put years, for example I also have a text box in which I have to put the year in which the book was edited.

0

If it is only valid if it is a valid number, you can do so too, similar to what you did.

Accepts so much int how much float, remembering that float will only work with . guy 10.28 to accept , is already another problem.

function valida() {
    	var el = document.getElementById("ano");
    	var str = el.value;
    	var num = parseFloat(str);
      
      if(isNaN(num)){
        alert('Não é um número válido '+num);
      }else{
        alert('É um número válido!! '+num);
      }
	}
<input type="text" class="nome2" id="ano" value="">

<button type="button" onclick="valida()">OK</button>

Browser other questions tagged

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