如何在不添加JavaScript验证变量的情况下执行HTML验证?

时间:2018-10-30 20:37:59

标签: javascript html forms validation

我在站点附近搜索了此问题,但找不到所需的答案。我正在制作一个根据用户输入产生成绩百分比和字母成绩的表格。

但是,我还需要验证表格。当前,计算功能可以正常工作,但是HTML代码在提交之前无法验证,因此用户可以提交任何内容,并且仍可以运行。我可以轻松进行验证而无需创建JavaScript验证变量吗?

谢谢!

HTML:         

<p><b>Name: </b> <input type="text" size="20" id="student" required><span class="required">*</span></p>

<p><b>Assignment 1: </b><input type="number" id="assign1" size=10 value="" name="onlynumbers" min="0" max="25" required><span class="required">*</span></p>

<p><b>Assignment 2: </b><input type="number" id="assign2" size=10 value="" name="onlynumbers" min="0" max="25" required><span class="required">*</span></p>

<p><b>Assignment 3: </b><input type="number" id="assign3" size=10 value="" name="onlynumbers" min="0" max="25" required><span class="required">*</span></p>

<p><b>Assignment 4: </b><input type="number" id="assign4" size=10 value="" name="onlynumbers" min="0" max="25" required><span class="required">*</span></p>

<p><b>Midterm Exam: </b><input type="number" id="midterm" size=10 value="" name="onlynumbers" min="0" max="100" required><span class="required">*</span></p>

<p><b>Final Exam: </b><input type="number" id="final" size=10 value="" name="onlynumbers" min="0" max="100" required><span class="required">*</span></p>

<p><b>Final Project: </b><input type="number" id="project" size=10 value="" name="onlynumbers" min="0" max="100" required=""><span class="required">*</span></p>

<p>
<button onclick="calculator()">Submit</button>

<input type="reset" value="Reset">

</p>
</form>

JavaScript:

    function calculator()
    {
        var student=document.getElementById('student').value;
        var grade1=parseFloat(document.getElementById('assign1').value*1);
        var grade2=parseFloat(document.getElementById('assign2').value*1);
        var grade3=parseFloat(document.getElementById('assign3').value*1);
        var grade4=parseFloat(document.getElementById('assign4').value*1);
        var grade5=parseFloat(document.getElementById('midterm').value*1);
        var grade6=parseFloat(document.getElementById('final').value*1);
        var grade7=parseFloat(document.getElementById('project').value*1);
        var total=grade1 + grade2 + grade3 + grade4 + grade5 + grade6 + grade7;
        var average = total / 4

        document.getElementById('average').innerHTML = average;



        if ( average < 59.9 )
              document.writeln("<h1>Hello "+ student +", your grade percent is " + average +"%, and your letter grade is F.</h1>" );

            else if (average <= 63.9 && average >= 60 )
              document.writeln("<h1>Hello, "+ student +", your grade percent is " + average +"%, and your letter grade is D-.</h1>" );

            else if( average <= 66.9 && average >= 64 )
              document.writeln("<h1>Hello "+ student +", your grade percent is " + average +"%, and your letter grade is D.</h1>" );                        

            else if( average <= 69.9 && average >= 67 )
              document.writeln("<h1>Hello "+ student +", your grade percent is " + average +"%, and your letter grade is D+.</h1>" );

            else if( average <= 73.9 && average >= 70 )
              document.writeln("<h1>Hello "+ student +", your grade percent is " + average +"%, and your letter grade is C-.</h1>" );  

            else if( average <= 76.9 && average >= 74 )
              document.writeln("<h1>Hello "+ student +", your grade percent is " + average +"%, and your letter grade is C.</h1>" );

            else if( average <= 79.9 && average >= 77 )
              document.writeln("<h1>Hello "+ student +", your grade percent is " + average +"%, and your letter grade is C+.</h1>" );

            else if( average <= 83.9 && average >= 80 )
              document.writeln("<h1>Hello "+ student +", your grade percent is " + average +"%, and your letter grade is B-.</h1>" );

            else if( average <= 86.9 && average >= 84 )
              document.writeln("<h1>Hello "+ student +", your grade percent is " + average +"%, and your letter grade is B.</h1>" );

            else if( average <= 89.9 && average >= 87 )
              document.writeln("<h1>Hello "+ student +", your grade percent is " + average +"%, and your letter grade is B+.</h1>" );

            else if( average <= 93.9 && average >= 90 )
              document.writeln("<h1>Hello "+ student +", your grade percent is " + average +"%, and your letter grade is A.</h1>" );

            else if( average <= 100 && average >= 94 )
              document.writeln("<h1>Hello "+ student +", your grade percent is " + average +"%, and your letter grade is A+.</h1>" );

    }

2 个答案:

答案 0 :(得分:1)

您可以使用完全不需要任何JavaScript的HTML form validation属性:

<form action="#" method="post">
  <input name="test" required>
  <input name="ssNumber" pattern="d{3}-d{2}-d{4}" required>
  <input type="email" required>
  <div>
    <button>Submit</button>
  </div>
</form>

或者,您可以循环遍历JavaScript中的HTML表单字段,并分别进行检查。

但是,无论您做什么,您都必须了解,并且可以轻松地绕过任何客户端验证技术,因此,在数据被处理之后,应在服务器上再次进行任何客户端验证。提交。

现在,您的代码还有其他一些问题,这些问题主要与冗余和简单有关。因此,这是一个重做的示例。有关更多详细信息,请参见嵌入式注释:

// Get all the element references you'll need repeated access to just once:
let btnCalc = document.querySelector("button[type='button']");
let btnSubmit = document.querySelector("button[type='submit']");
let form = document.querySelector("form");
let report = document.getElementById("reportingArea");
let rStudent = document.getElementById("rStudent");
let rAverage = document.getElementById("rAverage");
let rLetterGrade = document.getElementById("rLetterGrade");
let gradePercent = document.querySelector("input[name='gradePercent']");
let gradeLetter = document.querySelector("input[name='gradeLetter']");

// No need to set variables for each grade. Just gather all the grade inputs
// up into an Array for easy looping later.
let assignments = Array.prototype.slice.call(document.querySelectorAll(".assign"));

// Don't set variables to properties of elements, set them to the elements
// themselves so that if you decide later you want to look at some other
// aspect of the element, you don't have to query for the same element again later.
var student = document.getElementById('student');
let average =  document.getElementById('average');

// Set up event handlers in JavaScript, not with inline HTML event attributes
// And, you want to do your validation on the form's submit event, not the submit
// button's click event.
btnCalc.addEventListener("click", calculate);
form.addEventListener("reset", function(){
  // Hide the reporting area
  report.classList.add("hidden");
  
  // Show the Calc button and hide the submit button
  btnSubmit.classList.add("hidden");
  btnCalc.classList.remove("hidden");
});

function calculate() {
  const assignmentCount = 4;
  
  rStudent.textContent = student.value;    // Set up the reporting area details
  
  // Loop over the assignments and calculate the average
  let sum = 0;           
  assignments.forEach(function(assign){
    sum += +assign.value;
  });
  
  let average = (sum / assignmentCount).toFixed(2);
  rAverage.textContent = average;
   
  if(average < 59.9){
    rLetterGrade.textContent = "F";
  } else if (average <= 63.9 && average >= 60 ) {
    rLetterGrade.textContent = "D-";
  } else if( average <= 66.9 && average >= 64 ) {
    rLetterGrade.textContent = "D";
  }  else if( average <= 69.9 && average >= 67 ) {
    rLetterGrade.textContent = "D+";
  } else if( average <= 73.9 && average >= 70 ) {
    rLetterGrade.textContent = "C-";
  } else if( average <= 76.9 && average >= 74 ) {
    rLetterGrad.textContente = "C";
  } else if( average <= 79.9 && average >= 77 ) {
    rLetterGrade.textContent = "C+";
  }  else if( average <= 83.9 && average >= 80 ) {
    rLetterGrade.textContent = "B-";
  }  else if( average <= 86.9 && average >= 84 ) {
    rLetterGrade.textContent = "B";
  }  else if( average <= 89.9 && average >= 87 ) {
    rLetterGrad.textContente = "B+";
  }  else if( average <= 93.9 && average >= 90 ) {
    rLetterGrade.textContent = "A";
  }  else {
    rLetterGrade.textContent = "A+";
  }
  
  // Update the hidden form fields
  gradePercent.value = average;
  gradeLetter = rLetterGrade.textContent;  
  
  // Show the reporting area now that it's complete
  report.classList.remove("hidden");
  
  // Show the Submit button and hide the calculate button
  btnSubmit.classList.remove("hidden");
  btnCalc.classList.add("hidden");
}
/* All styling should be done with CSS, not in HTML */
.row { margin:.5em 0; }
label { display:inline-block; width:8em; font-weight:bold; }
.assign { width:10em; }
.hidden { display:none; }

/* Styling to show validity status of element */
input:invalid { box-shadow:0 0 1px rgba(255, 0, 0, .5); }
input:valid { box-shadow:0 0 1px rgba(0, 255,0, .5); }
<form>
  <!-- A paragraph is for a complete thought or idea, not just to put stuff on its own line.
       A div is for putting stuff on their own line. -->
  <div class="row">
    <!-- Use labels to associate a caption with a form field. -->
    <label for="student">Name: </label>
    <!--
         The default type of an input is text, so you don't need to say it.
         Also, the default size is 20, so you don't need to say that either.
         But, if you do want to style the element, do it with CSS. 
         And, simply add the 'required' attribute to make the field required.
         Also, every form field that will need to send its data to the server
         needs to have a 'name' attribute and value.
    -->
    <input id="student" name="student" required><span class="required">*</span>
  </div>

  <div>
    <label for="assign1">Assignment 1: </label>
    <!-- No need to specify the value="". That's the default. -->
    <input type="number" id="assign1" name="onlynumbers" min="0" max="25" class="assign" required>
    <span class="required">*</span>
  </div>

  <div class="row">
    <label for="assign2">Assignment 2: </label>
    <input type="number" id="assign2" name="onlynumbers" min="0" max="25" class="assign" required>
    <span class="required">*</span>
  </div>

  <div class="row">
    <label for="assign3">Assignment 3: </label>
    <input type="number" id="assign3" name="onlynumbers" min="0" max="25" class="assign" required>
    <span class="required">*</span>
  </div>

  <div class="row">
    <label for="assign4">Assignment 4: </label>
    <input type="number" id="assign4" name="onlynumbers" min="0" max="25" class="assign" required>
    <span class="required">*</span>
  </div>  

  <div class="row">
    <label for="midterm">Midterm Exam: </label>
    <input type="number" id="midterm" name="onlynumbers" min="0" max="100" class="assign" required>
    <span class="required">*</span>
  </div>

  <div class="row">
    <label for="final">Final Exam: </label>
    <input type="number" id="final"name="onlynumbers" min="0" max="100" class="assign" required>
    <span class="required">*</span>
  </div>

  <div class="row">
    <label for="project">Final Project: </label>
    <input type="number" id="project" name="onlynumbers" min="0" max="100" class="assign" required>
    <span class="required">*</span>
  </div>

  <div class="row">
    <button type="button">Calculate</button>
    <button type="submit" class="hidden">Submit</button> <!-- Hidden until you calculate -->
    <input type="reset" value="Reset">
  </div>
  
  <input type="hidden" name="gradePercent">
  <input type="hidden" name="gradeLetter">
</form>

<div id="reportingArea" class="hidden">
  <!-- Instead of writing out largely the same thing over and over with document.writeln
       in JavaScript, just prepare a template area that we can inject the details into.
       We'll keep this section hidden until we're ready to show it. -->
  <h1>
    Hello <span id="rStudent"></span>, your grade percent is <span id="rAverage"></span>% 
    and your letter grade is <span id="rLetterGrade"></span>
  </h1>
</div>

答案 1 :(得分:-1)

您可以使用onBlur事件进行输入。您可以根据输入使用不同的功能。

<input type="text" onblur="myFunction()">

这里还有更多https://www.w3schools.com/jsref/event_onblur.asp