如何一次验证所有字段?

时间:2016-04-01 09:11:35

标签: javascript jquery html css

我需要一次验证所有字段,我的意思是如果我在第一个字段中输入文本,其余字段应显示错误消息。

例如,如果我按下带有空字段的提交按钮,则应显示错误消息。

我的Java脚本如下所示:

 function check() 
  var fName = document.getElementById('mFirstName');
  var lName = document.getElementById('mLastName');
  var filter = /^[a-zA-Z0-9]+$/;
  if (!filter.test(fName.value)) {
    document.getElementById("mfnameValidate").style.display = "block";
    fName.focus();
    return false;
}

if (!filter.test(lName.value)) {
    document.getElementById("mlNmaeValidate").style.display = "block";
    lName.focus();
    return false;
}
function hideError() {
document.getElementById("mfnameValidate").style.display = "none";
} 
function hideError2() {
document.getElementById("mlNmaeValidate").style.display = "none";
}

我的HTML代码:

<form:form method="post" onsubmit="return check();" action="SignUp"  modelAttribute="memberBean">
<form:input type="text" class="input" name='mFirstName' id='mFirstName' path='mFirstName' placeholder='First Name' onkeydown="hideError()" />
 <span id="mfnameValidate">"First Name should not be blank"</span>
 <form:input type="text" class="input" name='mLastName' id='mLastName' path='mLastName' placeholder='Last Name'  onkeydown="hideError2()" />
 <span id="mlNmaeValidate">"Last Name should not be blank"</span>

我的.css:

<style>
 span {
 color: red;
 display: none;
  }
  </style>

2 个答案:

答案 0 :(得分:1)

尝试这样:

&#13;
&#13;
    app/console generate:doctrine:entities <Your Bundle>
    app/console doctrine:schema:update --dump-sql
    app/console doctrine:schema:update --force
&#13;
document.forms["theForm"].onsubmit = function(e) {
  var allInput = getAllElementsWithAttribute('required');
  for (key in allInput) {
    if (!allInput[key].value) {
      e.preventDefault();
      allInput[key].className += allInput[key].className.indexOf('invalid') > -1 ? '' : 'invalid';
    } else {
      console.log(key)
      allInput[key].className = allInput[key].className.replace(/\binvalid\b/, '');
    }
  }
}

function getAllElementsWithAttribute(attribute) {
  var matchingElements = [];
  var allElements = document.getElementsByTagName('*');
  for (var i = 0, n = allElements.length; i < n; i++) {
    if (allElements[i].getAttribute(attribute) !== null) {
      // Element exists with attribute. Add to array.
      matchingElements.push(allElements[i]);
    }
  }
  return matchingElements;
}
&#13;
.error {
  display: none;
  color: Red;
}
.invalid+.error {
  display: block;
}
&#13;
&#13;
&#13;

还有一个小提琴:https://jsfiddle.net/rmrinmoy/xnLzjhgy/3/

答案 1 :(得分:0)

请使用以下链接使用jquery验证。 http://jqueryvalidation.org/files/demo/