user12799076
user12799076

Reputation:

JavaScript validate input doesn't work correctly

I want to validate that when pressing a button it is validated if the input, in case it is empty, an alert appears and that it focuses on that input, but what happens is that if it is empty, the alert comes out but sends me to another page.

Form:

<html>

<head>
  <title>prueba</title>
</head>

<body>
  <form onsubmit="control()" action="https://stackoverflow.com">
    <input type="text" id="uname" placeholder="Ingrese usuario..." name="uname">
    <input type="password" placeholder="Ingrese contraseña..." name="psw">
    <button type="submit">Iniciar sesión</button>
  </form>

  <script>
    function control() {
      if (document.getElementById('uname') == "") {
        alert("El campo no puede estar vacío.");
        document.getElementById('uname').focus();
        return false;
      }
      return true;
    }
  </script>
</body>

</html>

The script doesn't work 'cause when i press the button and input text is empty this no shows the alert and redirect me to page. Any sugerence?

Upvotes: 1

Views: 45

Answers (2)

MMRahman
MMRahman

Reputation: 319

You can try this as well. This will check onblur field by field.

var validating = false; 
function control(element) {
  var id = element.id;

  var errors = {
      psw : 'enter password',
      uname : 'enter Username'
  };
if (document.getElementById(id).value === '') {
    if (id in errors) {
      if(validating == false) {
        validating = true
        alert(errors[id]);
        setTimeout(function(){
          document.getElementById(id).focus();
          validating = false;
        }, 1);
     }
    }
}
}
<html>
    <head>
        <title>prueba</title>
    </head>
    <body>
        <form action="https://stackoverflow.com" >
        <input id="uname" name="uname" value="" type="text" onblur="control(this)" autocomplete='off'>
        <input type="password" placeholder="Ingrese contraseña..." name="psw" id="psw" value=""  onblur="control(this)" autocomplete='off' >
                    <button type="submit">Iniciar sesión</button>
            </form>
    </body>
</html>

Upvotes: 0

TommyBs
TommyBs

Reputation: 9646

Change your if statement to the following so you actually check if the 'value' of the field is empty. As it stands you're checking if the DOMElement is equal to ""

   if (document.getElementById('uname').value == "") {

Upvotes: 1

Related Questions