Validating JavaScript fields

2

I have a problem with a code that transforms the Phone field into this format: (51) 96321-5465 . However, every time I click Submit, the form says in the field: "É preciso que o formato corresponda ao exigido. "and does not let the form send, the code is this:

<!-- Formatar campo telefone -->
<script type="text/javascript">
/* Máscaras ER */
function mascara(o,f){
    v_obj=o
    v_fun=f
    setTimeout("execmascara()",1)
}
function execmascara(){
    v_obj.value=v_fun(v_obj.value)
}
function mtel(v){
    v=v.replace(/\D/g,"");             //Remove tudo o que não é dígito
    v=v.replace(/^(\d{2})(\d)/g,"($1) $2"); //Coloca parênteses em volta dos dois primeiros dígitos
    v=v.replace(/(\d)(\d{4})$/,"$1-$2");    //Coloca hífen entre o quarto e o quinto dígitos
    return v;
}
function id( el ){
    return document.getElementById( el );
}
window.onload = function(){
    id('telefone').onkeypress = function(){
        mascara( this, mtel );
    }
}
</script> <!-- FIM Formatar campo telefone -->

And where do I want the field to inform the phone:

< div class="campo">
    < label for="telefone">Telefone</label>
    < input type="text" id="telefone" name="telefone" placeholder="Somente números" size="16" maxlength="15"  value="" pattern="[0-9]+$"/>
< /div>

Why is this message showing up and not even sending the field not having a required?

    
asked by anonymous 24.05.2017 / 15:20

2 answers

2

You are using the pattern attribute to validate the input data. Removing everything will be fine, and validation will only occur via Javascript:

<div class="campo">
    <label for="telefone">Telefone</label>
    <input type="text" id="telefone" name="telefone" placeholder="Somente números" size="16" maxlength="15"  value="">
</div>
    
24.05.2017 / 15:59
3

DEMO

It is not necessary to remove the pattern attribute but rather to adapt it.

(^[\d-\)\(]+$)

HTML

<div class="campo">
<label for="telefone">Telefone</label>
<input type="text" id="telefone" name="telefone" placeholder="Somente números" size="16" maxlength="15"  value="" pattern="(^[\d-\)\(]+$)"/>

  • \d dígito o mesmo que [0-9]
  • -\)\( caracteres aceitos
24.05.2017 / 16:40