表单验证不显示消息

时间:2014-05-06 01:10:27

标签: javascript html forms

我正在尝试获取我的javascript以验证电话号码输入并在用户输入错误信息时显示消息。我有两个其他输入设置,所以我复制其中一个,只是用phoneNumber替换名称,但没有结果。没有HTML替代品,我必须使用它进行评估。

这里我只包含了电话号码输入的代码。 http://jsfiddle.net/29ZNV/

HTML

    <form>
        <label for="phoneNumber"><span class="textStyle">Phone Number*</span>
        <input type="text" id="phoneNumber"><br>
        <span id="phoneMessage" class="message">You must have a valid phone number</span>
         </label>
<input type="submit" id="submit" value="Submit"/>
</form>

JAVASCRIPT

var phoneInput = document.querySelector ('#phoneNumber');
var submitButton = document.querySelector('#submit');

function displayError(fieldname, message) {
    var input_field = document.querySelector('#' + fieldname);
    var error_box = document.querySelector('#' + fieldname + 'Message');

    addClass (input_field, 'error');
    error_box.style.display = 'block';

    error_box.innerHTML = message;
}

function hideError(fieldname){
    var input_field = document.querySelector('#'+fieldname);
    var error_box = document.querySelector('#'+fieldname+'Message');
    removeClass (input_field, 'error');
    error_box.style.display = 'none';
}

function addClass(html_element,class_str) {
    if(html_element.className.indexOf(class_str) == -1){
        html_element.className += ' '+class_str;
    }
}

function removeClass(html_element, class_str){
    if(html_element.className.indexOf(class_str) != -1){
        html_element.className = html_element.className.replace(class_str, '');
    }
}

  phoneInput.onblur = function(){
    if(!phoneNumberInput.value){
     valid = false;        
    displayError('phoneNumber', 'Please enter your number');
    }else if(!isValidPhoneNumber(phoneNumberInput.value)){
    valid = false; 
    displayError('phoneNumber', 'The phone number field is invalid');
    }else{
        hideError('phoneNumber');
    }
}


submitButton.onclick = function(){
    var nameIsValid = checkName();
    var emailIsValid = checkEmail();
    var phoneNumberIsValid = checkphoneNumber();

    var valid = nameIsValid && emailIsValid && phoneNumberIsValid;
    return valid;
 }

function isValidPhoneNumber(str){
    var phoneNumberPattern = new RegExp('^[a-zA-Z \s\'-]{1,}$');
}

3 个答案:

答案 0 :(得分:1)

看起来您只需将phoneMessage代替phoneNumberMessage放在此行中:

<span id="phoneNumberMessage" class="message">You must have a valid phone number</span>

答案 1 :(得分:0)

注意:此答案纯粹是作为表单验证的替代解决方案

使用HTML5输入类型很容易做到这一点。在这种情况下,您可以非常轻松地使用以下内容:

<form>
    <label for="phoneNumber">
        <span class="textStyle">Phone Number*</span>
        <input type="tel" pattern="((\+|00)[0-9]{2}|0)[ -]*[1-9]([ -]*[0-9]){8}" id="phoneNumber">
    </label>
    <button id="submit">Submit</button>
</form>

这就是一切。无需JavaScript。只需看看this demo(其中包含有效性的CSS突出显示)。

在尝试输入示例国家/地区代码+10时,该模式将允许包含或不包含空格或短划线的10个数字,或允许使用001010的国家/地区代码前缀。 test this regex

这适用于所有现代浏览器,但不适用于某些旧版浏览器。 MDN表示这仅在IE10 +中受支持,并且在Safari中不支持。其他浏览器支持它,除了它们的旧版本,它们几乎不再使用了。

答案 2 :(得分:0)

您的代码中有很多内容。我已经冒昧地清理了一些并简化了验证逻辑,以实现更大的可扩展性。您可以查看整个工作代码here,但要点如下:

<强> HTML
不要显示和隐藏每个字段的错误消息,而应考虑使用无序列表来显示错误消息。这种做法很常见,可以大大简化HTML和JS:

<form>
  <ul class="errors"></ul>
  <label for="phone_number">*Phone Number
    <input name="phone_number" type="text"/>
  </label>
  <br>
  <input type="submit"/>
</form>

<强> JavaScript的:
这就是验证逻辑的核心所在。正如其他人所提到的,您可以使用HTML5属性来验证您的数据,但这缺乏跨浏览器兼容性并且易受用户操纵(尽管后一点也适用于JS验证; 您应该始终验证在服务器端也是安全的

window.onload = function() {
  var form = document.querySelector('form');

  // listen for the form submission
  form.addEventListener('submit', validate, false);

  function validate(e) {
    var errors  = {},
        valid   = true,
        errorUL = document.querySelector('.errors'),
        node;

    // clear the errors list
    errorUL.innerHTML = '';

    // iterate through the inputs and validate each one using
    // a case statement
    [].forEach.call(e.target, function(input) {
      switch (input.name){
        case 'phone_number':
          if (!validPhoneNumber(input.value)) {
            // add the appropriate error message to the errors object
            errors[input.name] = "Phone number is not valid";
            valid = false; // set the 'valid' flag to false
          }
        // Add more case statements as you need them
        // Example:
        // case 'home_address': 
        // ...
      }
    });

    // if the form is invalid
    if (!valid) {
      // prevent the submission
      e.preventDefault();

      // loop through the errors and add the messages to the errorUL
      for (e in errors) {
        node = document.createElement('li');
        node.innerHTML = errors[e];
        errorUL.appendChild(node);
      }
    }
  }

  // This function will return the validated phone number or null
  // You may want to use this function to convert your phone number
  // string to an integer. This function will accept phone numbers 
  // in the following forms:
  //
  // 123.456.7890
  // 1234567890
  // (123)456-7890
  // (123)-456-7890
  // 123-456-7890
  // 123 456 7890
  function validPhoneNumber(n) {
    var r = /^\(?(\d{3})\W{0,2}(\d{3})\W?(\d{4})$/,
        match = r.exec(n);

    // if the phone number is valid, return the number as an int
    // if the number is invalid, return null
    return match ? match.slice(1).join('')|0 : null;
  }
}

以上JS做了几件事:

  1. 它查询<form>元素并为'submit'添加事件侦听器。这比使用onclick侦听器更可取,因为它允许您直接访问表单,以及输入及其值。
  2. 事件侦听器将validate函数作为事件处理程序附加。此函数将用于迭代表单中的各种输入(假设您有多个输入)并验证每个输入。您会注意到我使用switch语句按其name属性处理各种输入。这使您可以在添加新输入时轻松添加其他验证。有关switch语句如何工作的更多信息,请查看the documentation
  3. 在验证了所有输入后,validate函数将检查valid标志是真还是假。如果表单无效(即valid = false),则每条错误消息都会包含在<li>标记中并附加到<ul class='errors'>
  4. validPhoneNumber(n)功能获取用户输入的电话号码,并使用 RegEx 检查其是否有效。如果数字有效,则以整数形式返回;如果没有,该函数将返回null。您可以选择使用此功能来标准化用户的格式。如果您愿意,可以将电话号码作为整数。
  5. 希望这能让您了解使用JS验证HTML表单的好方法。但请记住,没有多少客户端验证可以替代服务器上的验证。