JavaScript:提交期间未验证表单值

时间:2014-12-02 20:13:44

标签: javascript html

在这段代码中,当我尝试提交表单时,我在输入框上做了一些验证,如果user-name输入框的值小于6并且没有值,那么,我正在警告{ {1}}。当我按下提交按钮时,此alert("dshddhhdhdhh");无效。哪里出错了?请。

alert

1 个答案:

答案 0 :(得分:3)

您的表单元素名为user-name,但您正在检查username。变化

if (loginForm.username.value.length < 6 ){

if (loginForm['user-name'].value.length < 6 ){

&#13;
&#13;
window.onload = function(){
  document.getElementsByName("user-name")[0].value="";
  document.getElementsByName("password")[0].value="";
  document.getElementsByName("password1")[0].value="";
  document.getElementsByName("email")[0].value="";
  document.getElementsByName("url")[0].value="";
  document.getElementById("FormSubmit").style.display="none";
  document.querySelector('span[class="user-name"]').style.display="none";
  document.querySelector('span[class="password"]').style.display="none";
  document.querySelector('span[class="password1"]').style.display="none";
  document.querySelector('span[class="url"]').style.display="none";

  document.getElementsByName("user-name")[0].focus();
}

var formElem = document.getElementsByName("loginForm")[0];
formElem.onsubmit = function(){
  var returnValue=true;
  if (loginForm['user-name'].value.length < 6 ){
    returnValue = false;
    alert("dshddhhdhdhh");
    return returnValue;
  }
}
&#13;
<form name="loginForm" method="post">
    <input type="text" name="user-name" placeholder="Firstname Lastname"/>
    <span class="user-name">Name should not be empty</span>
    <input type="password" name="password" placeholder="Password"/>
    <input type="password" name="password1" placeholder="Confirm password"/>
    <span class="password1">Password does not be match</span><span class="password">Password does not be match</span>
    <input type="email" name="email" placeholder="Email" required/>
    <input type="url" name="url" placeholder="Website"/>
    <span class="url">Invalid Website URL</span>
    <input name="submit" type="submit" value="Submit"/>
</form>
&#13;
&#13;
&#13;