验证JavaScript中的表单

时间:2018-11-09 07:25:46

标签: javascript html

我的代码需要验证所有问题,并仅在选择了每个输入后才提交。我认为这是一个逻辑问题,因为我的代码在先工作,但是我似乎找不到出错的地方。

当前正在发生的情况是,即使其余输入为空,也仅在第一个问题中没有选择时提醒用户。我真的不确定为什么会这样,并尝试重写了几次。我曾尝试重写过几次,但真的很感谢任何帮助。

<li><input type="button" value="Click" onclick="calcDate()"></li>
<br/><br/>
<li><label id="web">Do you ever think about how you would design a web page?</label></li>
<li><input type="radio" value="no" name="rad1" /><span>No</span></li>
<li><input type="radio" value="yes" name="rad2" /><span>Yes</span></li>
<li><label for="prior">Which the following are your main priorities? If none, select N/A</label></li>
<li>
  <select name="prior">
    <option selected="" value="Default">**Please select one of the following**</option>
    <option value="ux">Ease of Use</option>
    <option value="inter">Graphics & Content</option>
    <option value="data">The Data Collected</option>
    <option value="secure">Securing the site from possible attacks</option>
    <option value="pm">Overseeing the creation of software</option>
    <option value="none">None</option>
  </select>
</li>
<li><label id="res">Do you enjoy conducting research, asking questions, and building reports?</label></li>
<li><input type="radio" value="no" name="rad3" /><span>No</span></li>
<li><input type="radio" value="yes" name="rad4" /><span>Yes</span></li>
<li><label for="text1">Does hacking a system or stopping a system from being hacked sound interesting to you? Type Yes or No:</label></li>
<li><textarea name="text1" id="text1" maxlength="3"></textarea></li>
<li><input type="submit" value="Finished!" onsubmit="return validateForm()"></li>
<li><input type="reset" id="reset"></li>


<script>
  //form validation
  function validateForm() {
    //creating variables
    var radio1 = document.quiz.rad1;
    var radio2 = document.quiz.rad2;
    var valOps = document.quiz.prior;
    var radio3 = document.quiz.rad3;
    var radio4 = document.quiz.rad4;
    var tx1 = document.quiz.text1;
    //calling functions
    vWebRes(radio1, radio2, radio3, radio4);

    valOps(prior);
    vData(radio3, radio4);
    vLength(tx1);
    vCheck2(Text);

    if (vWebRes(radio1, radio2, radio3, radio4)) {
      if (valOps(prior)) {
        if (vData(radio3, radio4)) {
          if (vLength(tx1)) {
            if (vCheck2(tx1)) {
              return false;
            }
          }
        }
      }
    }


    //validating radio buttons
    function vWebRes(radio1, radio2) {
      x = 0;
      if ((radio1.checked) || (radio2.checked)) {
        x++;
      }
      if (x == 0) {
        alert('You forgot a question!')
        radio1.focus();
        return false;
      } else {
        return true;
      }
    }
    //validating checkbox options
    function valOps(prior) {
      if (prior.value == "Default") {
        alert('Select an option from the drop-down menu');
        prior.focus();
        return false;
      } else {
        return true;
      }
    }
    //validation question 3
    function vData(radio3, radio4) {
      z = 0;
      if ((radio3.checked) || (radio4.checked)) {
        z++;
      }
      if (z == 0) {
        alert('You forgot a question!')
        radio3.focus();
        return false;
      } else {
        return true;
      }
    }

    //validating text length
    function vLength(tx1) {
      var txLength = tx1.value.length;
      if (txLength > 3) {
        alert("That is an incorrect entry, try again.");
        tx1.focus();
        return false;
      } else {
        return true;
      }
    }
    //validating text entry
    function vCheck2(tx1) {
      if ((tx1 == "Yes" || tx1 == "yes") || (tx1 == "No" || tx1 == "no")) {
        tx1.focus();
        return true;
      } else {
        alert('You entered an incorrect value, try again')
        tx1.focus();
        return false;
      }
    }
  }
</script>

2 个答案:

答案 0 :(得分:0)

您可能希望将输入字段(值 .val )添加到这样的数组中,并将没有 .val 的相应ID添加到另一个数组中:

var arrayName = [a, b, c]; //just a mock example
var arrayNameInputs = [x, y, z]; //just a mock example, these should contain inputs with .val

然后遍历结果并检查空索引:

if(arrayNameInputs.indexOf("") !== -1){  //checks if there are any empty fields at all
    for(i=0; i < arrayName.length; i++){
        if(arrayName[i].val() == ""){
            //do something, red outline, alert, w/e
        }
    }
}

只需确保所有默认值均为“”,而不是“默认”即可。
这与您尝试的方式有所不同,但是对我有用,所以您可能想看看。

答案 1 :(得分:0)

我认为您需要对广播输入进行分组。
只需重命名您的无线电输入即可。
另请参见:https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/radio

已编辑: 新的工作代码。我在代码中写了注释,阅读并尝试运行代码。


代码:

//form validation
function validateForm() {
  // you can use form
  // see here: https://developer.mozilla.org/en-US/docs/Web/API/RadioNodeList/value
  var quiz = document.forms[0];

  // get those input 
  var radio1 = quiz.elements['radio1'];
  var radio2 = quiz.elements['radio2'];
  var selectedPrior = quiz.elements['prior'];
  var textArea1 = quiz.elements['textArea1'];

  // and get your answer
  var formData = {
    radio1: radio1.value,
    selectedPrior: selectedPrior.value,
    radio2: radio2.value,
    textArea1: textArea1.value,
  }

  // you can see your answer in console [f12] developer mode 
  console.log("Data", formData);

  // do your validation
  //suggest not to nest your if clause because it will hard to read
  // do it one by one and by your questions order

  //if radio1 is blank
  if (formData.radio1 == "") {
    alert('You forgot a question!')
    // in order to focus on radio input , you must specific which one you need to focus
    // so I give each of them unique id
    // choose one to focus
    document.getElementById("radio1Yes").focus();

    // document.getElementById("radio1No").focus();

    // just for information, radio input focus is not visible

    // if you want to stop when this is blank you just call return, it will end the function
    // so the other validation will carry on when the radio1 is filled up
    return;
  }

  //if selectedPrior is blank
  if (formData.selectedPrior == "") {
    alert('You forgot a question!')
    selectedPrior.focus();
    return;
  }

  //if radio2 is blank
  if (formData.radio2 == "") {
    alert('You forgot a question!')

    document.getElementById("radio2No").focus();
    return;
  }

  //if textArea1 is blank
  if (formData.textArea1 == "") {
    alert('You forgot a question!')
    textArea1.focus();
    return;
  }
  
  
  // after all value validate then you can go on submit the form
  quiz.submit();

}
<!-- give your question into a form and give it a name -->
<form name="quiz">
  <ol>
    <li><input type="button" value="Click" onclick="calcDate()"></li>
    <!-- You [must] group your radio input in order to get the value correctly-->
    <li>
      <label id="web">Do you ever think about how you would design a web page?
          <div>
            <input type="radio" id="radio1No" value="no" name="radio1" /><span>No</span>
          </div>
          <div>
            <input type="radio" id="radio1Yes" value="yes" name="radio1" /><span>Yes</span>
          </div>
        </label>
    </li>
    <li>
      <label for="prior">Which the following are your main priorities? If none, select N/A</label>
      <div>
        <select name="prior">
          <!-- give the place holder option empty value [ just like this -> value="" ] -->
          <option value="">**Please select one of the following**</option>
          <option value="ux">Ease of Use</option>
          <option value="inter">Graphics & Content</option>
          <option value="data">The Data Collected</option>
          <option value="secure">Securing the site from possible attacks</option>
          <option value="pm">Overseeing the creation of software</option>
          <option value="none">None</option>
        </select>
      </div>
    </li>
    <li>
      <!-- remember to group your radio input -->
      <label id="res">Do you enjoy conducting research, asking questions, and building reports?</label>
      <div>
        <input type="radio" value="no" id="radio2No" name="radio2" /><span>No</span>
      </div>
      <div>
        <input type="radio" value="yes" id="radio2Yes" name="radio2" /><span>Yes</span>
      </div>
    </li>
    <li>
      <!-- just for suggestion: you still can use radio input on this -->
      <label for="textArea1">Does hacking a system or stopping a system from being hacked sound interesting to you?
          Type Yes or No:</label>
      <div>
        <textarea name="textArea1" id="textArea1" maxlength="3"></textarea>
      </div>
    </li>
    <li>
      <!-- I suggest to use onclick and do submition of form in javascript -->
      <input type="button" value="Finished!" onclick="validateForm()">
      <!-- you need to put this reset into a form to get it function correctly -->
      <input type="reset" id="reset">
    </li>
  </ol>
</form>