如何以响应方式获取JavaScript来验证HTML5表单文本框中的信息?

时间:2019-04-07 18:40:12

标签: javascript html5

我正在尝试为演示任务构建功能信用卡验证脚本。我正在尝试使JavaScript对focus()从文本框更改为文本框做出反应。一旦我使JavaScript具有反应性,那么我想针对特定参数验证该数据。

我尝试将onchange方法直接添加到HTML5中,但是某些方法无法正常工作。我乐于接受所有建议,我在僵局中花费了太长时间。

HTML

<h2>Payment
<img style="visibility: hidden" class="mastercard" 
src="https://img.icons8.com/color/48/000000/mastercard.png">
<img style="visibility: hidden" class="visacard" 
src="https://img.icons8.com/color/48/000000/visa.png">
<img style="visibility: hidden" class="discovercard" 
src="https://img.icons8.com/color/48/000000/discover.png">
<img style="visibility: hidden" class="amexcard" 
src="https://img.icons8.com/color/48/000000/amex.png">
</h2>
    <div class="form-group">
      <label for="name-on-card">Name on Card</label>
      <input class="cc_name" type="text" name="card-name" class="form-control" placeholder="">
    </div>
    <div class="form-group">
      <label for="cc-number">Credit card number</label>
      <input type="text" class="form-control" id="cc_number" name="cc_number" placeholder="" maxlength="16">
    </div>
    <div class="">
      <select class="month_year_select" name="month" id="month">
        <option value="">exp month</option>
      </select>
    </div>
    <div class="">
      <select class="month_year_select" id="year" name="year">
        <option value="">exp year</option>
      </select>
    </div>
    <div class="CVV">
      <label for="cc-cvv">CVV</label>
      <input type="text" class="form-control" id="cc-cvv" name="cc-cvv" placeholder="" maxlength="4">
    </div>
      <button type="submit" class="myButton"style = "float:right;">Place Order</button>
  </form>  

JavaScript

<script type="text/javascript">
  var creditError="Error with Credit Card information";
  var CWError="Error with CW";

document.getElementbyID("cc-cvv").onchange=function(){function CWcheck()};

document.getElementbyID("cc_number").onchange=function(){function creditCheck()};

document.getElementbyID("cc_name").onchange=function(){function upperFunction()};


function CWcheck()
  {
    if (document.forms["LeftCheck"]["cc-cvv"].value.length < 3 ||document.forms["LeftCheck"]["cc-cvv"].value.length>=5){
      alert(CWError);
      cdocument.forms["LeftCheck"]["cc-cvv"].value.value=" ";
    }
    else if(document.forms["LeftCheck"]["cc-cvv"].value.match(/^[A-Za-z]+$/)){
      alert(CWError);
      document.forms["LeftCheck"]["cc-cvv"].value=" ";
    }
    else if(document.forms["LeftCheck"]["cc-cvv"].value.match(/^[-+]?[0-9]+\.[0-9]+$/)) { 
      alert(CWError);
      document.forms["LeftCheck"]["cc-cvv"].value=" ";
    }
    else 
      break;
  }

function upperFunction() {
  document.getElementsByClassName("cc_name").value.toUpperCase();
  }


function creditCheck() {
  {
    if (document.forms["LeftCheck"]["cc_number"].value.length < 15 ||document.forms["LeftCheck"]["cc_number"].value.length>16){
      alert(creditError);
      document.forms["LeftCheck"]["cc_number"].value=" ";
    }
    else if(document.forms["LeftCheck"]["cc_number"].value.match(/^[A-Za-z]+$/)){
      alert(creditError);
      document.forms["LeftCheck"]["cc_number"].value=" ";
    }
    else if(document.forms["LeftCheck"]["cc_number"].value.match(/^[-+]?[0-9]+\.[0-9]+$/)) { 
      alert(creditError);
      document.forms["LeftCheck"]["cc_number"].value=" ";
    }
    else 
      if(document.forms["LeftCheck"]["cc_number"].value.match(/^(?:3[47][0-9]{13})$/)){
        document.getElementsByClassName('amexcard').style.visibility="visable";
        document.forms["LeftCheck"]["cc_number"].value=" ";
        }
      else if(document.forms["LeftCheck"]["cc_number"].value.match(/^(?:4[0-9]{12}(?:[0-9]{3})?)$/)){
        document.getElementsByClassName('visacard').style.visibility="visable";
        document.forms["LeftCheck"]["cc_number"].value=" ";
        }
      else if(document.forms["LeftCheck"]["cc_number"].value.match(/^(?:5[1-5][0-9]{14})$/)){
        document.getElementsByClassName('mastercard').style.visibility="visable";
        document.forms["LeftCheck"]["cc_number"].value=" ";
        }
      else if(document.forms["LeftCheck"]["cc_number"].value;=.match(/^(?:6(?:011|5[0-9][0-9])[0-9]{12})$/)){
        document.getElementsByClassName('discovercard').style.visibility="visable";
        document.forms["LeftCheck"]["cc_number"].value=" "
        }        
      else {
        alert(creditError)
        this.clear()
        }
  }    

我希望文本框能够在输入信用卡号时进行验证;它将检查输入的数字之外的任何内容,数字的节奏与卡类型匹配或重置字段,并在“付款”标题旁边显示该卡的图像。

Alex的Checksum Validation效果很好,这部分使我可以简化图像设置。到目前为止,我的代码已更新为以下

更新的HTML

<form method="POST" action="/checkout" class = "LeftCheck" name="LeftCheck" id="LeftCheck">
<h2>Payment
<img style="visibility: hidden" class="mastercard" 
src="https://img.icons8.com/color/48/000000/mastercard.png">
<img style="visibility: hidden" class="visacard" 
src="https://img.icons8.com/color/48/000000/visa.png">
<img style="visibility: hidden" class="discovercard" 
src="https://img.icons8.com/color/48/000000/discover.png">
<img style="visibility: hidden" class="amexcard" 
src="https://img.icons8.com/color/48/000000/amex.png">
</h2>
    <div class="form-group">
      <label for="name-on-card">Name on Card</label>
      <input class="cc_name" type="text" name="card-name" class="form-control" placeholder="">
    </div>
    <div class="form-group">
      <label for="cc-number">Credit card number</label>
      <input type="text" class="form-control" id="cc_number" name="cc_number" placeholder="" maxlength="16">
    </div>
    <div class="">
      <select class="month_year_select" name="month" id="month">
        <option value="">exp month</option>
      </select>
    </div>
    <div class="">
      <select class="month_year_select" id="year" name="year">
        <option value="">exp year</option>
      </select>
    </div>
    <div class="CVV">
      <label for="cc-cvv">CVV</label>
      <input type="text" class="form-control" id="cc-cvv" name="cc-cvv" placeholder="" maxlength="4">
    </div>
      <button type="submit" class="myButton"style = "float:right;">Place Order</button>
  </form>

以及我的JavaScript的更新的发行区域

document.getElementById('cc_number').addEventListener('change',pictureCheck);
  function pictureCheck()
  {
    var ccNum = this.value;
    if (ccNum.length = 15)
    {
      document.getElementsById('amexcard').style.display='';
    }
    else if(ccNum.value.match(/^(?:4[0-9]{12}(?:[0-9]{3})?)$/))
    {
      document.getElementsById('visacard').style.display='';
    }
    else if(ccNum.value.match(/^(?:5[1-5][0-9]{14})$/))
    {
      document.getElementsById('mastercard').style.display='';
    }
    else (ccNum.value;=.match(/^(?:6(?:011|5[0-9][0-9])[0-9]{12})$/)) 
    {
      document.getElementsById('discovercard').style.display='';
    }
  }

4 个答案:

答案 0 :(得分:0)

您可以使用JQuery执行此操作。在输入字段之间切换时,可以运行验证脚本。

$("#id1, #id2").focus(function() {
  alert("Focus changed.");
  //run validator
});

答案 1 :(得分:0)

我注意到您使用document.forms["LeftCheck"]["cc-cvv"]访问表单的字段。由于您未包含表单开始标记,因此我想确保您表单的name字段设置为LeftCheck,而不是ID,因为我之前遇到过这个问题。

您还可以使用document.getElementbyID()访问要将onchange侦听器应用于的元素。该方法实际上是document.getElementbyId(),最后一个字母不大写。这可能是您的事件未触发的原因。

将事件附加到select元素的方式也不正确。您可以简单地做到这一点:

document.getElementbyID("cc-cvv").onchange = CWcheck;

或者

document.getElementbyID("cc-cvv").onchange = function() { CWcheck();};

最后一件事是您使用正则表达式来验证信用卡字段的输入。但是,您可以通过检查输入是否与无效模式匹配来完成此操作,如果匹配则引发错误。尽管这可行,但最好检查输入是否匹配有效的模式,如果不匹配,则会引发错误。这样可以使您的验证代码更加健壮,并确保您没有可能通过验证的无效边缘情况。

答案 2 :(得分:0)

使用内联onblur事件

<input type="text" onblur="CWcheck()" />

答案 3 :(得分:0)

您的javascript部分完全错误。让我展示一下应该如何工作。

document.getElementById('cc-cvv').addEventListener('change', CWcheck); //recommended way
document.getElementById('cc_number').onchange = creditCheck; //it is OK too

function CWcheck() { //function name should conventionally start with lower case but isn't big deal
  //"this" is the element which fired the event
  if (!/^\d{3,4}$/.test(this.value)) {
    this.value = '';
    this.focus();
    alert('CVV is 3 or 4 digits');
  }
}

function creditCheck() {
  // hide cc logos
  var ccImgs = document.querySelectorAll('h2 img');
  for (var i = 0, ccImg; ccImg = ccImgs[i]; ++i) {
    ccImg.style.visibility = 'hidden';
  }
  var ccNum = this.value.replace(/\D/g, ''); //remove all non-digits
  if (ccNum.length < 15 /*15 is amex*/ || ccNum.length > 16) {
    alert('CC number is 15 or 16 digits');
    this.focus();
    return false;
  }
  //implement Luhn algorithm
  var check = ccNum.split('') //get array
    .reverse()
    .map(function(el, index) {
      return el * (index % 2 + 1); //multiply even positions by 2
    })
    .join('') //combine array of strings
    .split('')
    .reduce(function(a, b) { //sum digits
      return a + (b - 0);
    }, 0);
  if (!check || (check % 10)) { //checksum should be none-zero and dividable by 10
    alert('Incorrect checksum of CC');
    this.focus();
    return false;
  }
  //test passed. show card logo
  if (/^5[1-5]/.test(ccNum))
    document.querySelector('h2 img.mastercard').style.visibility = 'visible';
  else if (/^4/.test(ccNum))
    document.querySelector('h2 img.visacard').style.visibility = 'visible';
  else if (ccNum.length == 15 && /^3[47]/.test(ccNum))
    document.querySelector('h2 img.amexcard').style.visibility = 'visible';
  else if (/^6011/.test(ccNum))
    document.querySelector('h2 img.discovercasd').style.visibility = 'visible';
  //and so on
  else {
    alert('CC number doesn\'t match known any CC issuer');
    this.focus();
    return false;
  }

  //test passed. format the string
  this.value = ccNum
    .replace(/^(\d{4})(\d{4})(\d{4})(\d+)$/, '$1 $2 $3 $4');
}
<h2>Payment
  <img style="visibility: hidden" class="mastercard" src="https://img.icons8.com/color/48/000000/mastercard.png">
  <img style="visibility: hidden" class="visacard" src="https://img.icons8.com/color/48/000000/visa.png">
  <img style="visibility: hidden" class="discovercard" src="https://img.icons8.com/color/48/000000/discover.png">
  <img style="visibility: hidden" class="amexcard" src="https://img.icons8.com/color/48/000000/amex.png">
</h2>
<div class="form-group">
  <label for="name-on-card">Name on Card</label>
  <input class="cc_name" type="text" name="card-name" class="form-control" placeholder="">
</div>
<div class="form-group">
  <label for="cc-number">Credit card number</label>
  <input type="text" class="form-control" id="cc_number" name="cc_number" placeholder="" maxlength="20">
</div>
<!--<div class="">
  <select class="month_year_select" name="month" id="month">
    <option value="">exp month</option>
  </select>
</div>
<div class="">
  <select class="month_year_select" id="year" name="year">
    <option value="">exp year</option>
  </select>
</div>-->
<div class="CVV">
  <label for="cc-cvv">CVV</label>
  <input type="text" class="form-control" id="cc-cvv" name="cc-cvv" placeholder="" maxlength="4">
</div>

更新:添加了卡号中的CC发卡行。