Custom form validation for phone number


#1

I am trying to add phone validation on form submit.
Main goal is: if phone starts not on “39” or “+39” add this numbers before the number and submit. Code is added via script manager just before tag.
But it doesn’t work on submit. Form submitting and script bellow not even triggers. But script works fine in console and jsfiddle.
And I don’t have any errors in browser console.
This form in only one form on the page.
Any ideas?

<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

This sounds like something that might be in @Stefano’s wheelhouse as he has a lot of leads that come through phone calls.


#3

Hey guys!

We haven’t had a need for this just yet - so I can’t give you a hand unfortunately. I know @Hristian has likely seen this before and can probably help.

Let us know if you get it to work!