电话号码的Javascript表单验证

时间:2017-07-14 23:03:03

标签: javascript html forms validation

尝试使用非常简单的验证创建表单,我很好奇两件事。

一个;如何检查表单是否为空?

两个;在电话号码字段中,我如何才接受以这种格式的号码:

xxx-xxxx(其中X是数字)

这是我到目前为止所做的:

HTML:

<form onsubmit="return false" method="post" name="myForm">

    <div class="form-block">
       <label>Name: </label>
       <input type="text" name="name" id="name" />
     <span id="name-error" class="error"></span>
</div>

<div class="form-block">
       <label>Phone Number: </label>
       <input type="text" name="phone" id="phone" />
     <span id="phone-error" class="error"></span>
</div>

       <input type="submit" id="mysubmit" name="submit" onclick="validate()" />
</form>

CSS:

 a, p, h1, h2, h3, h4, h5, h6, li, label, span {
   font-family: sans-serif;
 }

 #mysubmit {
   display: block;
   margin-top: 10px;
 }

 span.error {
   color: red;
   font-weight: bold;
 }

 .form-block {
    display: block;
    width: 100%;
    margin: 10px 0;
   }

   label {
     display: inline-block;
    width: 150px;
    text-align: right;
  }

JS:

validate = function() {
    var name = document.getElementById("name").value;
  var phone = document.getElementById("phone").value;

  if(/^[a-zA-Z]*$/.test(name)) {
    document.getElementById("name-error").innerHTML = "Good.";
  } else {
    document.getElementById("name-error").innerHTML = "Invalid. Only letters.";
  }

  if(isNaN(phone)) {
  document.getElementById("phone-error").innerHTML = "Can only contain numbers";  
  } else {
   document.getElementById("phone-error").innerHTML = "Good."; 
  }

};

1 个答案:

答案 0 :(得分:0)

只需检查空字符串,即可测试表单元素的值是否为空。

我已经posted something可以帮助您访问和遍历表单字段。

// ES5: a very crude validation check
// your form field elements should share a class in order to collect them all
var formElements = document.querySelectorAll('.your-form-field-class');

// set a flag to keep track of whether you have an empty field
var containsEmptyField = false
    i,
    l = formElements.length;

    for (; i < l; i++) {
       if (formElements[i].value === '') {
        containsEmptyField = true;
        // do something in response to an empty field
        // the break is to stop looping since you've found 
        // a match 
        break;
       }    
   }

// ES6: a very crude validation check
const formElements = document.querySelector('#some-form').elements;
let containsEmptyField = false;
for (let element of formElements) {
   if (element.value === '') {
       containsEmptyField = true;
       break;
   }
}

我没有正确测试,但电话号码的正则表达式可能如下所示:

(/^(\d){3,3}\-(\d){4,4}$/).test(someNumber) 
// returns true if value matches or false if it doesn't