Jonathan Buitrago
Jonathan Buitrago

Reputation: 33

Basic js validation

I'm a beginner at JS and I want to do a basic HTML and JS validation. How can I do it with 2 inputs (number and submit)?

    var edad =  document.getElementById("edad"),
 	    numero = edad.numero

    function validacion(){
        if (numero >= 18) {
      	   alert("eres mayor de edad");
        } else {
           alert("eres menor de edad");
        }
    }


 	edad.addEventListener("submit", validacion);
    <!DOCTYPE html>
    <html>
    <head>
	
	    <title></title>
    </head>
    <body>
	    <div id="edad">
		   <input type="number" name="numero"  class="numero">
		   <input type="submit" name="btn" value="enviar" class="btn">
		   <script type="text/javascript" src="1.js"></script>
	   </div>
</body>
</html>

Upvotes: 1

Views: 106

Answers (2)

Himali Patel
Himali Patel

Reputation: 118

html :

<form name="myForm" action="/action_page.php" onsubmit="return validateForm()" method="post">
  Name: <input type="text" name="fname">
  <input type="submit" value="Submit">
</form>

js code:

function validateForm() {
  var x = document.forms["myForm"]["fname"].value;
  if (x == "") {
    alert("Name must be filled out");
    return false;
  }
}

Upvotes: 0

Scott Marcus
Scott Marcus

Reputation: 65883

You are setting up an event listener on submit, which points to a div, but a div doesn't have a submit event.

In addition, you need to get the value of the input, and compare that, not the input element itself.

Also, edad.numero is not the proper way to access the input element.

Lastly, all data that comes into JavaScript from HTML is a string, so you need to convert it to a number to do math with it.

If you set up a valid listener on a form element, and reference the input correclty the code will fire:

var edad =  document.getElementById("edad");
var numero = document.querySelector("input[name='numero']");

function validacion(event){
  event.preventDefault(); // prevents the form from submitting
  // The + converts the string to a number
  // And, you must get the value of the input, not the input itself
  if (+numero.value >= 18) {
    alert("eres mayor de edad");
  } else {
    alert("eres menor de edad");
  }
}

edad.addEventListener("submit", validacion);
<form id="edad">
  <input type="number" name="numero"  class="numero">
	<input type="submit" name="btn" value="enviar" class="btn">
</form>

Upvotes: 2

Related Questions