阻止提交非数字字段的表单

时间:2017-12-14 11:25:39

标签: javascript html

我正在尝试设置表单验证 - 这是有效的 - 但仅限于奇数,如果输入偶数,例如部件号TEST和数量2然后警报将出现,如果您输入数量3,则表单将提交。有什么想法吗?

的Javascript

<script type="text/javascript">
function allnumeric(inputtxt)
   {
      var numbers = /^[0-9]+$/;
      if(form2.qty.value.match(numbers) & (form2.product.value != ""))
      {
      return true;
      }
      else
      {
      alert('Please input numeric characters only or fill in the product field')
      {
      return false;
      }
   }  
   }
</script>

表格

<form id="form2" name="form2" method="post" action="booking-printlabel2.asp?insert=yes" onsubmit="return allnumeric()">


                <input name="product" type="text" id="product" style="height:55px;font-size:30pt;" size="10"/>


                <input name="qty" type="text" id="qty" style="height:55px;font-size:30pt;" size="3"/>


          <input type="submit" name="Print Labels2" id="Print Labels2" value="Print Labels" style="height:55px;font-size:30pt;"/>

    </form>

谢谢大家 - 这是错字,if(form2.qty.value.match(numbers) & (form2.product.value != "")) changed to if(form2.qty.value.match(numbers) && (form2.product.value != ""))现在可以了。

3 个答案:

答案 0 :(得分:1)

假设您正在定位html5:

<input name="qty" type="number" id="qty" style="height:55px;font-size:30pt;"/>

或者如果你真的想要输入type =&#34; text&#34;:

<input name="qty" type="text" id="qty" pattern="\d+" style="height:55px;font-size:30pt;"/>

另外,你有一个错字:

if(form2.qty.value.match(numbers) & (form2.product.value != ""))

应该是

if(form2.qty.value.match(numbers) && (form2.product.value != ""))

答案 1 :(得分:1)

在你的if条件中,你必须再添加一个if条件来检查奇数和偶数。你必须这样做:

if(form2.qty.value.match(numbers) & (form2.product.value != ""))
{
    var num = form2.qty.value;
    if(num%2 == 0) { 
        alert('Even number'); 
    } else {       
        return true; 
    }
}

答案 2 :(得分:1)

function allnumeric(inputtxt)
  {
      var numbers = /^[0-9]+$/;
      var qty = form2.qty.value;
      if(qty.match(numbers) && (form2.product.value != ""))
      {
        if(qty & 1) // even number
          return true;
        else
          alert('Even number');
        return false;
      }
      else
      {
        alert('Please input numeric characters only or fill in the product field')
        return false;
      }  
 }
<form id="form2" name="form2" method="post" action="booking-printlabel2.asp?insert=yes" onsubmit="return allnumeric()">


                <input name="product" type="text" id="product" style="height:55px;font-size:30pt;" size="10"/>


                <input name="qty" type="text" id="qty" style="height:55px;font-size:30pt;" size="3"/>


          <input type="submit" name="Print Labels2" id="Print Labels2" value="Print Labels" style="height:55px;font-size:30pt;"/>

    </form>