简体   繁体   中英

Form validation not working with vanilla js

I'm trying to do my first form validation with only Vanilla JS. I have a form, that has two selects in which you have to select your department and depending on this it will allow you to select another location. I made a script for this.

Now, when I relate another script which is formValidation, it doesn't work and I guess I'm doing the form validation well. I'm starting doing it so it only has one validation but it isn't working.

What could be the problem? When i wrote the form validation in the script file, it override the function or the selects so it didn't work. I don't know how to else doing a form validation because I'm new to JS and I'm not allowed to use jquery or anything.

Thanks

Here is the code pen:

https://codepen.io/yomiram/pen/abNMaMy

HTML :

<section id="formSection">
    <span class="textForm">Formulario</span>
    <hr>

    <form action="/" id="form" action="GET">
        <div class="form-group">
            <input type="text" placeholder="Nombre" id="name" class="input-control" required/>
            <input type="text" placeholder="Apellido" id="lastName" class="input-control" />
          </div>
        
          <div class="form-group">
            <input type="email" placeholder="E-mail" id="email" class="input-control" required/>
          </div>
        
          <div class="form-group">
            <select class="input-control" style="flex: 6" id="dpto" required>
                <option selected="selected" class="department">Departamento</option>
            </select>
            <select class="input-control" placeholder="Localidad" id="location" style="flex:6" required>
                <option selected="selected" class="department">Localidad</option>
            </select> 
          </div>

          <div class="form-group">
            <input type="number" id="ci" class="input-control" placeholder="C.I" style="flex:6" required/>
          </div>

          <div class="form-group">
            <input type="checkbox" name="conditions" id="conditions" required>
            <label for="conditions" id="conditions"> Acepto las bases y condiciones</label><br>
          </div>
          <div class="form-group">
            <input type="submit" id="formButton" class="formButton" value="Enviar">
        
          </div>
    </form>
</section>

SCRIPT JS (SELECT FUNCTION):

// DISPLAYING DATA IN SELECT

var dptosLocs = {
    "Artigas":["Artigas"," Bella Unión"],
    "Canelones":["Canelones"," Santa Lucía"],
    "Montevideo":["Montevideo"],
    "Salto":["Salto"," Daymán"," Arapey"]
};

var sel = document.getElementById('dpto');
var fragment = document.createDocumentFragment();

Object.keys(dptosLocs).forEach(function(dptosLoc, index) {
    var opt = document.createElement('option');
    opt.innerHTML = dptosLoc;
    opt.value = dptosLoc;
    fragment.appendChild(opt);
});

sel.appendChild(fragment);

document.getElementById("dpto").onchange = function() {defineDpto()};

function defineDpto() {
  var dpto = document.getElementById("dpto").value;

  if (dpto == "Artigas" ) {
    var sel = document.getElementById('location');
    var fragment = document.createDocumentFragment();

  Object.values(dptosLocs["Artigas"]).forEach(function(dptosLoc, index) {
    var opt = document.createElement('option');
    opt.innerHTML = dptosLoc;
    opt.value = dptosLoc;
    fragment.appendChild(opt)

    sel.appendChild(fragment);
}); 

  } else if (dpto == "Canelones") {
      document.getElementById('location').options.length = 0;

      var sel = document.getElementById('location');
      var fragment = document.createDocumentFragment();
    
      Object.values(dptosLocs["Canelones"]).forEach(function(dptosLoc, index) {
      var opt = document.createElement('option');
      opt.innerHTML = dptosLoc;
      opt.value = dptosLoc;
      fragment.appendChild(opt)

      sel.appendChild(fragment);
  });

  } else if (dpto == "Montevideo") {
      document.getElementById('location').options.length = 0;

      var sel = document.getElementById('location');
      var fragment = document.createDocumentFragment();
    
      Object.values(dptosLocs["Montevideo"]).forEach(function(dptosLoc, index) {
      var opt = document.createElement('option');
      opt.innerHTML = dptosLoc;
      opt.value = dptosLoc;
      fragment.appendChild(opt)

      sel.appendChild(fragment);
  });
  } else if (dpto == "Salto") {
      document.getElementById('location').options.length = 0;

      var sel = document.getElementById('location');
      var fragment = document.createDocumentFragment();
    
      Object.values(dptosLocs["Salto"]).forEach(function(dptosLoc, index) {
      var opt = document.createElement('option');
      opt.innerHTML = dptosLoc;
      opt.value = dptosLoc;
      fragment.appendChild(opt)

      sel.appendChild(fragment);
  });
  }
}

FORM VALIDATION:

function validar (){
  var name, lastName, email, dpto, location, ci, condictions, expresion;

  name = document.getElementById('name').value;
  lastName = document.getElementById('lastName').value;
  email = document.getElementById('email').value;
  dpto = document.getElementById('dpto').value;
  location = document.getElementById('location').value;
  ci = document.getElementById('ci').value;
  conditions = document.getElementById('conditions').value;

  if (name === ""){
    alert("El campo nombre está vacío");
  }
}

You're missing the call to the validar function

<form .... onsubmit="return validar()">

Also validar should return false if the validation fails and true if it passes

The problem with your script is that the validar() function is never called. Please, remember, if you write a function and you never call it in your code, it will never be executed. What you have to do is to add the call to your validar() function in the onsubmit event of the form.

<form action="/" id="form" action="GET" onsubmit="return validar();">

And your validar() function should return false if the validation is not verified for the form.

if (name === ""){
    alert("El campo nombre está vacío");
    return false;
}
return true;

You should take a look at how events are called in javascript when dealing with forms.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM