JavaScript表单验证功能:循环每个项目

时间:2016-11-11 19:02:17

标签: javascript jquery html

我有一个表单输入元素列表,我想在其上运行循环。从结果中,我需要运行一些条件语句,以便我可以使用它们的名称属性来验证它们。我已经使用了jQuery并使用 .each 方法来循环它们。因此,我可以为无效的输入元素添加/删除类名。

用文字描述有点难。但是下面的代码块有意义:

JSFiddle



quoted form of

do shell script "open -a " & quoted form of fileappli & " " & quoted form of fileargument

function formValid() {
  var valid = true;

  $('form input').each(function() {
    if ($(this).val() == '') {
      valid = false;
      $(this).addClass('red-border');
    } else if (true /* if "tel" is not a number */ ) { // <- here I want to validate using input name attribute
      valid = false;
      $(this).addClass('red-border');
    } else {
      $(this).removeClass('red-border');
    }
  });

  return valid;
}

$('form').on('submit', function(event) {
  event.preventDefault();

  if (formValid()) {
    alert('Yay!');
  }
});
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:1)

查看小提琴 https://jsfiddle.net/t9ayvken/

CSS:

.red-border {
  border-color: red;
}

HTML:

<form action="#">

  <p>
    <input class="must-validate" type="text" name="name">
  </p>
  <p>
    <input class="must-validate" type="text" name="tel">
  </p>
  <p>
    <input class="must-validate" type="text" name="email">
  </p>

  <p>
    <button type="submit">Submit</button>
  </p>

</form>

JQuery的:

/*validation functions for each input type*/
function validateName(event){
    var $this = $(this);
  /* validation is done here */
  if(false){
   $this.removeClass('red-border');
  }
  else {
    /* not valid*/  
    $this.addClass('red-border');
  }
}
function validateTel(event){

}
function validateEmail(event){

}

/*add validation event handlers*/
$(document).on('validate','[name="name"]',validateName);
$(document).on('validate','[name="tel"]',validateTel);
$(document).on('validate','[name="email"]',validateEmail);


function formValid() {
    var valid = true;

  /*Trigger validation events for all required inputs*/
  $('input.must-validate').trigger('validate');


 /* After validation is complete check to see if any are invalid */      
  if( $('input.must-validate.red-border').length ){
    alert('the form is invalid');
    valid = false;
  } 

  return false;
  //return valid;
}

$('form').on('submit', function(event) {
    event.preventDefault();

  if ( formValid() ) {
    alert('Yay!');
  }
});

答案 1 :(得分:0)

我建议返回错误列表而不是布尔标志。

&#13;
&#13;
function formValid() {
  var errorMsgs = [];

  $('form input').each(function() {
    var msg = [],
        val = $(this).val();
    
    // Check blanks
    if (val == '') 
      msg.push( `${$(this).attr('name')} is blank`);
    
    // Check numbers
    if ($(this).attr('name') === 'tel' && isNaN(val))
      msg.push( `${$(this).attr('name')} is not a number`);
    
    // Handle results
    if (msg.length > 0){
      errorMsgs.push(...msg);
      $(this).addClass('red-border');
    } else {
      $(this).removeClass('red-border');
    }
  });

  return errorMsgs;
}
$('button').on('click', function(event) {

  var errors = formValid();
  if (errors.length === 0) {
    alert('Yay!');
  } else {
    alert(errors.join('\r'));
  }
});
&#13;
.red-border {
  border-color: red !important;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="#">

  <p>
    <input type="text" name="name">
  </p>
  <p>
    <input type="text" name="tel">
  </p>
  <p>
    <input type="text" name="email">
  </p>

  <p>
    <button type="submit">Submit</button>
  </p>

</form>
&#13;
&#13;
&#13;