用于特定数字的表单验证javascript

时间:2015-11-08 11:09:16

标签: javascript jquery forms validation

我想提出另一个条件,其中手机号码应该包含仅以5开头的8位数字。(例如:52024050)。任何帮助



function formValidation() {
  var mobile = document.forms["form"]["mobile"].value;

  // red expression 
  var checkNumbers = /^[0-9 ]+$/;

  if (mobile == null || mobile == "") {
    error[error.length] = ("Enter your mobile number");
    document.form.mobile.focus();
    $(document.forms["form"]["mobile"]).css("background-color", "blue");;
  } else if (mobile != null || mobile != "") {
    if (!checkNumbers.test(mobile)) {
      error[error.length] = ("Enter Only numeric Characters for mobile phone");
      document.form.mobile.focus();
      $(document.forms["form"]["mobile"]).css("background-color", "blue");
    }

<form name="form" onsubmit="return formValidation()" action="process.html">

  Mobile phone:&nbsp&nbsp&nbsp&nbsp&nbsp
  <input type="text" name="mobile" id="mobile">

  <input id="submit" type="submit" name="submit" id="submit">
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:1)

您可以使用正则表达式,如下所示

/^5[0-9]{7}$/

Regex Demo and Explanation

  1. ^:行首
  2. 5:匹配5次
  3. [0-9]{7}:匹配0到9之间正好7次的任何数字
  4. $:行尾
  5. 我建议在pattern属性和maxlength中对元素本身使用正则表达式。

    &#13;
    &#13;
    input:valid {
      color: green;
    }
    input:invalid, span {
      color: red;
    }
    span {
      display: none;
    }
    input:invalid + span {
      display: block;
    }
    &#13;
    <input type="text" pattern="5[0-9]{7}" maxlength="8" />
    <span>Enter Only numeric Characters for mobile phone.</span>
    &#13;
    &#13;
    &#13;

    由于jQuery包含在页面中,我建议将其用于DOM操作和事件处理。

    HTML:

    <form name="form" action="process.html">
        Mobile phone:&nbsp&nbsp&nbsp&nbsp&nbsp
        <input type="text" name="mobile" id="mobile" pattern="5[0-9]{7}" maxlength="8">
    
        <input id="submit" type="submit" name="submit" id="submit">
    </form>
    

    JavaScript的:

    var mobilePattern = /^5[0-9]{7}$/;
    $('form[name="form"]').on('submit', function(e) {
        var mobile = $('#mobile').val();
    
        if (!mobilePattern.test(mobile)) {
            $('#mobile').css('background', 'blue').focus();
        }
    });
    

答案 1 :(得分:1)

你可以试试这个正则表达式:

var checkMobile = /^5[0-9]{7}$/;

^5 =&gt;从5开始

[0-9]{7}$ =&gt;接下来以7个数字结束