带有JavaScript的验证表单

时间:2019-04-14 16:12:06

标签: javascript validation

我正在尝试使用纯JavaScript创建表单验证。 我有两个要验证的元素,一个选择选项和一个复选框,但是我无法设法使选择选项起作用。

这是我第一次尝试,请耐心等待:

var registrationForm, elSelectGender, elGenderHint, elTerms, elTermsHint; // Declare variables
registrationForm = document.getElementById('registrationForm'); // Store elements
elSelectGender = document.getElementById('gender');
elGenderHint = document.getElementById('genderHint');
elTerms = document.getElementById('terms');
elTermsHint = document.getElementById('termsHint');
elName = document.getElementById('firstName');
elNameHint = document.getElementById('nameHint');

function checkName(event) {
  if (elSelectGender.valueOf() == null) { // If name not entered
    elNameHint.innerHTML = 'You must insert your name.'; // Show message
    event.preventDefault(); // Don't submit form
  }
}

function checkGender(event) {
  if (elSelectGender.valueOf() == 'Select an option:') { // If gender not selected
    elGenderHint.innerHTML = 'You must select a gender.'; // Show message
    event.preventDefault(); // Don't submit form
  }
}

function checkTerms(event) {
  if (!elTerms.checked) { // If check-box ticked
    elTermsHint.innerHTML = 'You must agree to the terms.'; // Show message
    event.preventDefault(); // Don't submit form
  }
}

//Create event listeners: submit calls checkTerms(), change calls packageHint()
registrationForm.addEventListener('submit', checkName, false);
registrationForm.addEventListener('submit', checkGender, false);
registrationForm.addEventListener('submit', checkTerms, false);
<!DOCTYPE HTML>
<html>
<form id="registrationForm" name="registrationForm" method="post" action="example.html">

  <div>
    <label for="firstName" class="input"> Name: </label>
    <input name="firstName" class="form-control" id="firstName" placeholder="First Name" type="text" />
    <div id="nameHint" class="warning"></div>
  </div>

  <div>
    <label for="gender" class="selectbox"> Gender: </label>
    <select id="gender">
      <option value="Select an option:">Select an option:</option>
      <option value="Male">Male</option>
      <option value="Female">Female</option>
      <option value="I prefer not to say">I prefer not to say</option>
    </select>
    <div id="genderHint" class="warning"></div>
  </div>

  <div>
    <input type="checkbox" id="terms" />
    <label for="terms" class="checkbox"> Check to agree to terms &amp; conditions</label>
    <div id="termsHint" class="warning"></div>
  </div>

  <input class="btn btn-primary" id="submitButton" type="submit" value="Sign up for G Holiday" />
</form>

</html>

我希望对所有三个元素都发出警告消息并进行验证。如果这三个元素之一未经验证,则不应转到下一页。 出于某种原因,它仅适用于复选框,其他两个元素将被忽略。

2 个答案:

答案 0 :(得分:2)

我会将选择和输入包装到label中,并使用CSS显示.warning错误消息。
比起我使用Array.prototype.some()来检查我的任何元素,没有比使用ev.preventDefault()来通过检查并显示警告:

const EL = sel => document.querySelector(sel),
  warning = (el, err) => [err, el.closest('label').classList.toggle('is-error', err)][0],
  noValue = el => warning(el, !el.value.trim()),
  noCheck = el => warning(el, !el.checked),
  checkFormRegistration = ev => {
    const isSomeInvalid = [
      noValue(EL('#firstName')),
      noValue(EL('#gender')),
      noCheck(EL('#terms'))
    ].some(b => b);
    if (isSomeInvalid) ev.preventDefault();
  };

EL('#registrationForm').addEventListener('submit', checkFormRegistration);
label.is-error > *{
  outline: 1px solid red;
  outline-offset: -1px;
}
label + .warning {
  display: none;
  color: red;
}
label.is-error + .warning {
  display: block;
}
<form id="registrationForm" name="registrationForm" method="post" action="example.html">

  <div>
    <label> Name:
      <input name="firstName" class="form-control" id="firstName" placeholder="First Name" type="text">
    </label>
    <div class="warning">Please, enter a name</div>
  </div>

  <div>
    <label> Gender: 
      <select id="gender">
        <option value="">Select an option:</option>
        <option value="Male">Male</option>
        <option value="Female">Female</option>
        <option value="I prefer not to say">I prefer not to say</option>
      </select>
    </label>
    <div class="warning">Please, select a gender</div>
  </div>

  <div>
    <label>
      <input type="checkbox" id="terms">
      Check to agree to terms &amp; conditions
    </label>
    <div class="warning">You must agree to the terms</div>
  </div>

  <input class="btn btn-primary" id="submitButton" type="submit" value="Sign up for G Holiday">
</form>

答案 1 :(得分:1)

我将valueOf()更改为value等于空(初始化表单时,该字段为空,而不是null)。

请确保您的HTML元素正确无误,我以前看错了,现在看来已经纠正了。

在用户纠正验证错误的情况下,我添加了else语句来处理错误。

仍然,这是对验证的一种简化,它需要做更多的工作(如min-length,max-length之类的东西,您可能也要考虑它们,以及一些评论者提到的消毒,修整,我会把它留给你)。

var registrationForm, elSelectGender, elGenderHint, elTerms, elTermsHint; // Declare variables
registrationForm = document.getElementById('registrationForm'); // Store elements
elSelectGender = document.getElementById('gender');
elGenderHint = document.getElementById('genderHint');
elTerms = document.getElementById('terms');
elTermsHint = document.getElementById('termsHint');
elName = document.getElementById('firstName');
elNameHint = document.getElementById('nameHint');

function checkName(event) {
  if (elName.value == '') { // If name not entered
    elNameHint.innerHTML = 'You must insert your name.'; // Show message
    event.preventDefault(); // Don't submit form
  } else {
    elNameHint.innerHTML = '';
  }
}

function checkGender(event) {
  if (elSelectGender.value == 'Select an option:') { // If gender not selected
    elGenderHint.innerHTML = 'You must select a gender.'; // Show message
    event.preventDefault(); // Don't submit form
  } else {
    elGenderHint.innerHTML = '';
  }
}

function checkTerms(event) {
  if (!elTerms.checked) { // If check-box ticked
    elTermsHint.innerHTML = 'You must agree to the terms.'; // Show message
    event.preventDefault(); // Don't submit form
  } else {
    elTermsHint.innerHTML = '';
  }
}

//Create event listeners: submit calls checkTerms(), change calls packageHint()
registrationForm.addEventListener('submit', checkName, false);
registrationForm.addEventListener('submit', checkGender, false);
registrationForm.addEventListener('submit', checkTerms, false);
<!DOCTYPE HTML>
<html>
<form id="registrationForm" name="registrationForm" method="post" action="example.html">

  <div>
    <label for="firstName" class="input"> Name: </label>
    <input name="firstName" class="form-control" id="firstName" placeholder="First Name" type="text" />
    <div id="nameHint" class="warning"></div>
  </div>

  <div>
    <label for="gender" class="selectbox"> Gender: </label>
    <select id="gender">
      <option value="Select an option:">Select an option:</option>
      <option value="Male">Male</option>
      <option value="Female">Female</option>
      <option value="I prefer not to say">I prefer not to say</option>
    </select>
    <div id="genderHint" class="warning"></div>
  </div>

  <div>
    <input type="checkbox" id="terms" />
    <label for="terms" class="checkbox"> Check to agree to terms &amp; conditions</label>
    <div id="termsHint" class="warning"></div>
  </div>

  <input class="btn btn-primary" id="submitButton" type="submit" value="Sign up for G Holiday" />
</form>

</html>