如果用户输入的值小于最小长度,则显示错误消息

时间:2015-04-03 03:54:47

标签: javascript html

如果用户输入<

我想显示错误消息最小长度 这是我的代码..

<!DOCTYPE>
<HTML>
<form name="form" action="action.php" method="post" onsubmit="return validate()">
  <span>Name</span><br>
  <input type="text" name="firstName" id="firstName" maxlength="20">
&nbsp;<label id="error"></label>&nbsp;<label id="errorAlpha">
  </label>&nbsp;<label id="errorMinOne"></label>
</HTML>

<javascript>
function validate()
{
  var valid = true;
  var alphabet =/^[a-zA-z ]+$/;

  if(firstName.value.match(alphabet) || firstName.value=="")
  {
    document.getElementById('errorAlpha').innerHTML=""; 
  }

  else
  {
    document.getElementById('errorAlpha').innerHTML="*Invalid Name";
    document.getElementById('errorMinOne').innerHTML="";
    valid=false;
  }

  if(firstName.value.length<2)
  {
    document.getElementById('errorMinOne').innerHTML="*Name is too short";
    valid =false;
  }

  else
  {
    document.getElementById('errorMinOne').innerHTML="";
  }
}

if(firstName.value=="" && lastName.value=="")
{
  document.getElementById('error').innerHTML="*Field is empty";
  document.getElementById('errorTwo').innerHTML="*Field is empty";
  document.getElementById('errorMinOne').innerHTML="";
  valid = false;
}

if(firstName.value!="" && lastName.value=="")
{
  document.getElementById('error').innerHTML="";
  document.getElementById('errorTwo').innerHTML="*Field is empty";
  valid = false;
}

if(firstName.value=="" && lastName.value!="")
{
  document.getElementById('error').innerHTML="*Field is empty";
  document.getElementById('errorTwo').innerHTML="";
  valid = false;
}

if(firstName.value!="" && lastName.value!="")
{
  document.getElementById('error').innerHTML="";
  document.getElementById('errorTwo').innerHTML="";
}
</javascript>

错误是当我输入1时它显示*无效的名称和*名称太短,我希望它只显示*无效的名称..请帮助谢谢

2 个答案:

答案 0 :(得分:1)

在每个if条款中,最后都会返回false:

if((firstName.value.match(alphabet) || firstName.value=="") && firstName.value.length<2)
{
    document.getElementById('errorMinOne').innerHTML="*Name is too short";
    return false;
}

答案 1 :(得分:0)

将前三个if else语句更改为:

if(firstName.value.match(alphabet) || firstName.value=="")
{
     document.getElementById('errorAlpha').innerHTML="";    
}
else
{
    document.getElementById('errorAlpha').innerHTML="*Invalid Name";
    document.getElementById('errorMinOne').innerHTML="";
    valid=false;
}
if((firstName.value.match(alphabet) || firstName.value=="") && firstName.value.length<2)
{
    document.getElementById('errorMinOne').innerHTML="*Name is too short";
    valid = false;
}