JS中电话号码的自定义验证

时间:2018-03-07 07:36:57

标签: javascript web unbounce

我正在尝试在表单提交上添加电话验证。 主要目标是:如果电话没有启动" 39"或" + 39"在数字前添加此数字并提交。 在body标签之后通过脚本管理器添加代码。 但它并不适用于提交。我在浏览器控制台中没有任何错误。

<form action="some.php" method="POST">
  <div class="fields">
    <div class="lp-pom-form-field single-line-text" id="container_nome">
      <label class="main lp-form-label" for="nome" id="label_nome" style="height: auto;">
        <span class="label-style">Nome e Cognome&nbsp;*</span>
      </label>
      <input type="text" id="nome" name="nome" placeholder="" class="ub-input-item single text form_elem_nome">
    </div>
    <div class="lp-pom-form-field single-line-text" id="container_telefono">
      <label class="main lp-form-label" for="telefono" id="label_telefono" style="height: auto;">
        <span class="label-style">Telefono&nbsp;*</span>
      </label>
      <input type="text" id="telefono" name="telefono" placeholder="" class="ub-input-item single text form_elem_telefono">
    </div>
  </div>
</form>

 window.onload = function() {
      var mainForm = document.forms[0];
      mainForm.addEventListener("submit", function validPhone() {
        var re = /^\+?\d{1,3}?[- .]?\(?(?:\d{2,3})\)?[- .]?\d\d\d[- .]?\d\d\d\d$/;
        var myPhone = '';
        var element = document.getElementById('telefono');
        if (element != null) {
          myPhone = element.value;
        }
        else {
          myPhone = null;
        }
        var myPhoneTrim = myPhone.trim().replace(/\s|\-|\(|\)/g, "");
        var valid = re.test(myPhoneTrim);

        if (myPhoneTrim.startsWith("39")) {
          myPhoneTrim = "+" + myPhoneTrim;
        } else if (!myPhoneTrim.startsWith("39") && !myPhoneTrim.startsWith("+39")) {
          myPhoneTrim = "+39" + myPhoneTrim;
        }
        return valid;
      });
    }

2 个答案:

答案 0 :(得分:0)

尝试使用string.match()

var matches = string.match(^39);代替if (myPhoneTrim.startsWith("39"))

var matches = string.match(^[+]39);

但是,我发现您的初始代码没有问题。你能发贴HTML吗?

答案 1 :(得分:0)

不确定您的HTML是什么样的或者您如何应用JS脚本,但在JSFiddle中运行它似乎很好:https://jsfiddle.net/7u2h3nqn/17/

JS:

var mainForm = document.getElementById("lp-pom-button-205");

mainForm.addEventListener("click", function validPhone() {

        var re = /^\+?\d{1,3}?[- .]?\(?(?:\d{2,3})\)?[- .]?\d\d\d[- .]?\d\d\d\d$/;
        var myPhone = '';
        var element = document.getElementById('telefono');

        if (element != null) {
          myPhone = element.value;
        }
        else {
          myPhone = null;
        }
        var myPhoneTrim = myPhone.trim().replace(/\s|\-|\(|\)/g, "");
        var valid = re.test(myPhoneTrim);

        if (myPhoneTrim.startsWith("39")) {
          myPhoneTrim = "+" + myPhoneTrim;
        } else if (!myPhoneTrim.startsWith("39") && !myPhoneTrim.startsWith("+39")) {
          myPhoneTrim = "+39" + myPhoneTrim;
        }

        console.log(myPhoneTrim);

        return valid;
})