无法使JavaScript SSN表单验证工作

时间:2014-04-06 21:28:24

标签: javascript forms

我是JS的新手,并且当有人在某个字段中输入SSN号码时尝试获取它,它会给他们一个警告,告诉他们不要在那里放一个SSN号码。

HTML:

<form name="card" action="#">
    <input type="text" name="field" class="name social" size="60" placeholder="First and Last Name">
    <input type="text" name="field" class="phone social" size="60" placeholder="Phone Number">
    <input type="text" name="field" class="email social" size="60" placeholder="Email(name@example.com)">

    <select class="select">
        <option value="My card has not yet arrived">My card has not yet arrived
        <option value="Direct Deposit">Direct Deposit
        <option value="Suggest a Card">Suggest a Card
        <option value="Issues with CARD.com">Issues with CARD.com
        <option value="Other">Other
    </select>

    <textarea name="field" class="text social " cols="60" rows="5" placeholder="How can we help you?"></textarea>
    <input type"submit" name="submit" class="subBtn" value="Submit" onclick="warnCC(document.card.field)">Submit</input>
</form>

JS:

<script>
  function warnCC()  
    {  

      var ssn = document.getElementsByTagName("input");
      // document.getElementsByClassName("social");
      var pattern = /^[0-9]{3}\-?[0-9]{2}\-?[0-9]{4}$/;
      if (ssn.value.match(pattern)) 
      {
        return true;
        alert("Please Do Not Enter SSN Info Into This Form");

      }
      else 
      {
        return false;
        alert("yay!")
      } 
    }
</script>

任何有关我出错的地方的帮助都会非常有帮助。我也更喜欢它是在&#34; onfocusout&#34;如果有人能就此提出建议。

3 个答案:

答案 0 :(得分:3)

getElementsByTagNamegetElementsByClassName都会返回元素的列表。该列表没有value属性。列表 中的每个项目都有value属性,但不是列表。

您需要循环浏览输入列表并根据需要处理每个输入,例如:

var list = /*...get the list using either method you have in your code...*/;
var index, input;
for (index = 0; index < list.length; ++index) {
    input = list[index];
    // input.value will be the value of this particular input
}

旁注:querySelectorAllgetElementsByClassName有更好的支持(例如,IE8有,但不是getElementsByClassName),所以如果你想使用类获取列表,最好的选择:

var list = document.querySelectorAll(".the-class-here");

答案 1 :(得分:0)

您还应该在从函数返回之前执行alert()...如果您希望显示alert()对话框。

答案 2 :(得分:0)

我调整了你的功能。你可以在这里看到它不作为:http://jsfiddle.net/tBqP2

  function warnCC() {

      var formElements = document.getElementsByTagName("input");
      for (var k in formElements) {
          // document.getElementsByClassName("social");
          var pattern = /^[0-9]{3}\-?[0-9]{2}\-?[0-9]{4}$/;
          if (formElements[k].value.match(pattern)) {
              alert("Please Do Not Enter SSN Info Into This Form");
              return false;
          }

      }
      return true;
  }