在 3 位和 6 位数字后插入空格或连字符,前缀为 +91

Inserting space or hyphen after 3 and 6 digits, and having prefix +91

本文关键字:连字符 前缀 空格 插入 位和 数字      更新时间:2023-09-26

我想在输入文本中有 +91 pefix,它可以保持不变,并且在输入数据后在第 3 位和第 6 位数字后获得空格或连字符......可能吗?这是我的代码,请帮忙!!提前谢谢你

   function ValidateMobNumber(txtMobId) {
      var fld = document.getElementById(txtMobId);
      if (fld.value == "") {
      alert("You didn't enter a phone number.");
      fld.value = "";
      fld.focus();
      return false;
     }
      else if (isNaN(fld.value)) {
      alert("The phone number contains illegal characters.");
      fld.value = "";
      fld.focus();
      return false;
     }
     else if (!(fld.value.length == 10)) {
      alert("The phone number is the wrong length. 'nPlease enter 10 digit mobile no.");
      fld.value = "";
      fld.focus();
      return false;
     }
    }
    </script>
    </head>
    <body>
    <input type="text" id="txtMB" />
    <!--Or Call on Button-->
    <input type="submit" id="btnVal" value="Save" onclick="return ValidateMobNumber('txtMB')" />

您正在寻找的正则表达式是:

^'+91 ?'d{3}([ -]{1})?'d{3}([ -]{1})?'d{3}$
/* valid are:
    +91 123 456-789
    +91123456789
    +91 123-456-789
    etc.
    the regex means: +91, optional space, 3 numbers, optional one space or hyphen, the same once again and three numbers at the end.
*/

当你想在JavaScript中测试正则表达式时,你需要使用方法.test,请参阅下面的代码。

<form onsubmit="return ValidateMobNumber('txtMB');">
    <input type="text" id="txtMB">
    <input type="submit" id="btnVal" value="Save">
<form>
<script>
    function ValidateMobNumber(txtMobId) {
        var fld = document.getElementById(txtMobId);
        var patt = /'+91 ?'d{3}([ -]{1})?'d{3}([ -]{1})?'d{3}$/;
        var res = patt.test(fld.value);
        alert(res); // just for testing to show you if phone number is valid or not, remove that
        return res;
    }
</script>

http://jsfiddle.net/yv4dyoLg/

看到您在验证功能中不需要 3 个条件,上面的代码是完整的,错误消息可能是"您插入了无效的电话号码"。

比我将返回值移动到公式onsubmit操作中,因为您可以使用 Enter 发送它。当您按回车按钮时,onclick不会在submit input上激活。