簡體   English   中英

表單驗證不適用於 vanilla js

[英]Form validation not working with vanilla js

我正在嘗試僅使用 Vanilla JS 進行我的第一次表單驗證。 我有一個表格,它有兩個選擇,您必須在其中選擇您的部門,並根據它允許您選擇另一個位置。 我為此編寫了一個腳本。

現在,當我關聯另一個名為 formValidation 的腳本時,它不起作用,我想我在表單驗證方面做得很好。 我開始這樣做,所以它只有一個驗證,但它不起作用。

可能是什么問題呢? 當我在腳本文件中編寫表單驗證時,它會覆蓋函數或選擇,因此它不起作用。 我不知道如何進行表單驗證,因為我是 JS 新手,不允許使用 jquery 或任何東西。

謝謝

這是代碼筆:

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>

腳本JS(選擇功能):

// 在 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);
  });
  }
}

表格驗證:

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");
  }
}

您錯過了對validar函數的調用

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

如果驗證失敗, validar應該返回 false,如果通過則返回 true

您的腳本的問題在於從未調用過 validar() 函數。 請記住,如果你編寫了一個函數並且你從來沒有在你的代碼中調用過它,它就永遠不會被執行。 您需要做的是在表單的 onsubmit 事件中添加對您的 validar() 函數的調用。

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

如果未驗證表單的驗證,則您的 validar() 函數應返回 false。

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

您應該看看在處理表單時如何在 javascript 中調用事件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM