Form validation using regex and Javascript

Asked

Viewed 1,361 times

1

I’m having difficulty validating my form, I’m trying to validate with Javascript, but until now I could not validate all fields.

It only validates the field that is last in the code. For example, in the code, it validates the name, but does not validate the phone. I’m doing it all together, HTML along with Javascript:

  function formatar(mascara, documento) {
    var i = documento.value.length;
    var saida = mascara.substring(0, 1);
    var texto = mascara.substring(i)

    if (texto.substring(0, 1) != saida) {
      documento.value += texto.substring(0, 1);
    }

  }


  function validar() {
    value = document.getElementById("nascimento").value;
    re = /^[0-9]{2}\/[0-9]{2}\/[0-9]{4}$/;
    if (re.test(value)) {
      document.troca.submit();
    } else {
      alert('Data de Nascimento Inválida');
      form.nascimento.focus();
      return false;
    }
  }


  function validar() {
    value = document.getElementById("cpf").value;
    re = /([0-9]{2}[\.]?[0-9]{3}[\.]?[0-9]{3}[\/]?[0-9]{4}[-]?[0-9]{2})|([0-9]{3}[\.]?[0-9]{3}[\.]?[0-9]{3}[-]?[0-9]{2})/g
    if (re.test(value)) {
      document.troca.submit();
    } else {
      alert('CPF Inválido');
      form.cpf.focus();
      return false;
    }
  }


  function validar() {
    value = document.getElementById("tel").value;
    re = /^[0-9]{2}-[0-9]{5}-[0-9]{4}/g;
    if (re.test(value)) {
      document.troca.submit();
    } else {
      alert('Telefone Inválido');
      form.tel.focus();
      return false;
    }
  }


  function validar() {
    value = document.getElementById("nome").value;
    re = /^[a-zA-ZéúíóáÉÚÍÓÁèùìòàçÇÈÙÌÒÀõãñÕÃÑêûîôâÊÛÎÔÂëÿüïöäËYÜÏÖÄ\-\ \s]+$/;
    if (re.test(value)) {
      document.troca.submit();
    } else {
      alert('Nome Inválido');
      form.nome.focus();
      return false;
    }
  }
<!DOCTYPE html>
<html lang="pt-BR">

<head>
  <title>Cadastro</title>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <!--===============================================================================================-->
  <link rel="icon" type="image/png" href="images/icons/favicon.ico" />
  <!--===============================================================================================-->
  <link rel="stylesheet" type="text/css" href="vendor/bootstrap/css/bootstrap.min.css">
  <!--===============================================================================================-->
  <link rel="stylesheet" type="text/css" href="fonts/font-awesome-4.7.0/css/font-awesome.min.css">
  <!--===============================================================================================-->
  <link rel="stylesheet" type="text/css" href="fonts/iconic/css/material-design-iconic-font.min.css">
  <!--===============================================================================================-->
  <link rel="stylesheet" type="text/css" href="vendor/animate/animate.css">
  <!--===============================================================================================-->
  <link rel="stylesheet" type="text/css" href="vendor/css-hamburgers/hamburgers.min.css">
  <!--===============================================================================================-->
  <link rel="stylesheet" type="text/css" href="vendor/animsition/css/animsition.min.css">
  <!--===============================================================================================-->
  <link rel="stylesheet" type="text/css" href="vendor/select2/select2.min.css">
  <!--===============================================================================================-->
  <link rel="stylesheet" type="text/css" href="vendor/daterangepicker/daterangepicker.css">
  <!--===============================================================================================-->
  <link rel="stylesheet" type="text/css" href="css/util.css">
  <link rel="stylesheet" type="text/css" href="css/main.css">
  <!--===============================================================================================-->

</head>

<body>

  <div class="limiter">
    <div class="container-login100">
      <div class="wrap-login100">
        <form class="login100-form validate-form" action="cadastro.php" method="POST" name="form" id="form" onsubmit="return validar();">
          <span class="login100-form-title p-b-26">
						Cadastrar Cliente
					</span>

          <div class="wrap-input100 ">
            <input class="input100" type="text" name="nome" id="nome" required autocomplete="off" />
            <span class="focus-input100" data-placeholder="Nome"></span>
          </div>

          <div class="wrap-input100 validate-input" data-validate="Telefone inválido">
            <input class="input100" type="Tel" name="tel" id="tel" required autocomplete="off" maxlength="13" minlength="13" OnKeyPress="formatar('##-#####-####', this)" />
            <span class="focus-input100" data-placeholder="Telefone"></span>
          </div>

          <div class="wrap-input100 validate-input" data-validate="Email inválido">
            <input class="input100" type="email" name="email" id="email" required autocomplete="off" />
            <span class="focus-input100" data-placeholder="E-mail"></span>
          </div>

          <div class="wrap-input100 validate-input" data-validate="Data inválida">
            <input class="input100" type="text" name="nascimento" id="nascimento" required autocomplete="off" maxlength="10" minlength="10" OnKeyPress="formatar('##/##/####', this)" />
            <span class="focus-input100" data-placeholder="Nascimento"></span>
          </div>

          <div class="wrap-input100 validate-input" data-validate="CPF inválido">
            <input class="input100" type="Tel" name="cpf" id="cpf" autocomplete="off" required maxlength="14" minlength="14" OnKeyPress="formatar('###.###.###-##', this)" />
            <span class="focus-input100" data-placeholder="CPF"></span>
          </div>

          <div class="container-login100-form-btn">
            <div class="wrap-login100-form-btn">
              <div class="login100-form-bgbtn"></div>
              <button type="submit" class="login100-form-btn" onclick="return validar()">
								Confirmar
							</button>
            </div>
          </div>
        </form>

        <div class="container-login100-form-btn">
          <div class="wrap-login100-form-btn">
            <div class="login100-form-bgbtn"></div><a href="painel.html"><button class="login100-form-btn">Voltar</button></a>
          </div>
        </div>
      </div>
    </div>
  </div>

  <div id="dropDownSelect1"></div>

  <!--===============================================================================================-->
  <script src="vendor/jquery/jquery-3.2.1.min.js"></script>
  <!--===============================================================================================-->
  <script src="vendor/animsition/js/animsition.min.js"></script>
  <!--===============================================================================================-->
  <script src="vendor/bootstrap/js/popper.js"></script>
  <script src="vendor/bootstrap/js/bootstrap.min.js"></script>
  <!--===============================================================================================-->
  <script src="vendor/select2/select2.min.js"></script>
  <!--===============================================================================================-->
  <script src="vendor/daterangepicker/moment.min.js"></script>
  <script src="vendor/daterangepicker/daterangepicker.js"></script>
  <!--===============================================================================================-->
  <script src="vendor/countdowntime/countdowntime.js"></script>
  <!--===============================================================================================-->
  <script src="js/main.js"></script>

</body>

</html>

2 answers

1


In the button type="submit", you call the function validar() when the button is clicked (onclick="return validar()"). But then, in the onsubmit of form, calls the function again. Then the first thing is to remove one of these calls. We can remove from the button and leave only on form.

Then you set several times the function validar. With this, the function is overwritten and only the last definition is valid (in the case, the one that validates the name). See an example of what happened in your case:

function validar() {
  alert('validar 1');
}
// criando a mesma função de novo
function validar() {
  alert('validar 2');
}
// e de novo
function validar() {
  alert('validar 3');
}

// o alert chamado será "validar 3"
validar();

When calling the function validar() above, an alert will be displayed with the text "validate 3". This happens because I set the function 3 times, and the third time overrides the previous ones. That’s what happened when you set several times your function validar().

To avoid this problem - and even organize the code - you should change the names, indicating what each function validates (for example, validarNome, validarCPF, etc.), and then have a function that validates everything, ie that calls all these functions.

Another detail is that you don’t need to call submit() within these functions. Placing the validation call in the onsubmit of form, just return true or false, whether the form will be submitted or not.

In the example below I’ve "cleaned" your HTML (removed the CSS classes, etc), just to focus on the validation engine itself.

function formatar(mascara, documento) {
  let i = documento.value.length;
  let saida = mascara.substring(0, 1);
  let texto = mascara.substring(i);

  if (texto.substring(0, 1) != saida) {
    documento.value += texto.substring(0, 1);
  }
}

function validarDtNasc() {
  let value = document.getElementById("nascimento").value;
  let re = /^[0-9]{2}\/[0-9]{2}\/[0-9]{4}$/;
  if (!re.test(value)) {
    // campo inválido, retorna false para o formulário não ser submetido
    alert('Data de Nascimento Inválida');
    document.form.nascimento.focus();
    return false;
  }
  return true;
}

function validarCPF() {
  let value = document.getElementById("cpf").value;
  let re = /([0-9]{2}[\.]?[0-9]{3}[\.]?[0-9]{3}[\/]?[0-9]{4}[-]?[0-9]{2})|([0-9]{3}[\.]?[0-9]{3}[\.]?[0-9]{3}[-]?[0-9]{2})/g;
  if (! re.test(value)) {
    // campo inválido, retorna false para o formulário não ser submetido
    alert('CPF Inválido');
    document.form.cpf.focus();
    return false;
  }
  return true;
}


function validarTel() {
  let value = document.getElementById("tel").value;
  let re = /^[0-9]{2}-[0-9]{5}-[0-9]{4}/g;
  if (! re.test(value)) {
    // campo inválido, retorna false para o formulário não ser submetido
    alert('Telefone Inválido');
    document.form.tel.focus();
    return false;
  }
  return true;
}

function validarNome() {
  let value = document.getElementById("nome").value;
  let re = /^[a-zA-ZéúíóáÉÚÍÓÁèùìòàçÇÈÙÌÒÀõãñÕÃÑêûîôâÊÛÎÔÂëÿüïöäËYÜÏÖÄ\-\ \s]+$/;
  if (!re.test(value)) {
    // campo inválido, retorna false para o formulário não ser submetido
    alert('Nome Inválido');
    document.form.nome.focus();
    return false;
  }
  return true;
}

// valida todos os campos
function validarTudo() {
  // se um deles for inválido, retorna false e o form não é submetido
  return validarNome() && validarTel() && validarDtNasc() && validarCPF();
}
<form name="form" id="form" onsubmit="return validarTudo();">
  <div>
    <label for="nome">Nome:</label>
    <input type="text" name="nome" id="nome" required autocomplete="off">
  </div>

  <div>
    <label for="tel">Tel:</label>
    <input type="text" name="tel" id="tel" required autocomplete="off" maxlength="13" minlength="13" onkeypress="formatar('##-#####-####', this)">
  </div>

  <div>
    <label for="email">Email:</label>
    <input type="email" name="email" id="email" required autocomplete="off">
  </div>

  <div>
    <label for="nascimento">Data Nascimento</label>
    <input type="text" name="nascimento" id="nascimento" required autocomplete="off" maxlength="10" minlength="10" onkeypress="formatar('##/##/####', this)">
  </div>

  <div>
    <label for="cpf">CPF:</label>
    <input type="text" name="cpf" id="cpf" autocomplete="off" required maxlength="14" minlength="14" onkeypress="formatar('###.###.###-##', this)">
  </div>

  <div>
    <button type="submit">Confirmar</button>
  </div>
</form>

Also note that to declare the variables I switched var for let - see here the difference among them.


About the validations

Regarding the validations themselves, it is important to highlight some points.

The name regex accepts multiple spaces. Fill in the field with only spaces and you will see that it is valid. It also accepts names without surname (writing only "John" is valid, it is up to you to check whether this is really valid or not in your system) something like that be more precise, evaluate if you need something so complex or leave to make a more accurate validation in backend.

In CPF, it is interesting to validate also the check digits, take a look in this question for more details (and do some searches on the site and on the internet in general, what are not lacking are examples for you to base).

On the regular expressions, you can use \d, which is a synonym for [0-9], as described in documentation. That is to say:

// em vez dessa
let re = /^[0-9]{2}\/[0-9]{2}\/[0-9]{4}$/;

// pode usar essa
let re = /^\d{2}\/\d{2}\/\d{4}$/;

On the use of regex to validate dates, I comment a little in this answer and in the second half of this other answer, and there are also examples in this question. But perhaps it’s best to follow the recommendation of this answer and instead of regex, use language resources that are specific to treat dates, such as the object itself Date (there is also several examples on the website) or even a specific lib, such as the Moment js..

And if you want, you can also change the field to input type="date", not forgetting to check the browser compatibility (and the documentation suggests a workaround for browsers that do not support this type of input).

And don’t forget to validate all this information on backend.

0

  1. Separating your code into Javascript/HTML can help a lot for future development

  2. In your HTML, the handler for the "click" is onclick="return validar()". Its function is to validate:

function validar() {
    value = document.getElementById("cpf").value;
    re = /([0-9]{2}[\.]?[0-9]{3}[\.]?[0-9]{3}[\/]?[0-9]{4}[-]?[0-9]{2})|([0-9]{3}[\.]?[0-9]{3}[\.]?[0-9]{3}[-]?[0-9]{2})/g
    if (re.test(value)) {
        document.troca.submit();
    } else {
        alert('CPF Inválido');
        form.cpf.focus();
        return false;
    }
}

Only the number is being verified. Clearly, you would have to change your code to verify each input field, and manually you will have a great job, not counting the effort to maintain this code. Take a look at frameworks that can help you; I suggest looking at links like https://jqueryvalidation.org/documentation/ and http://form.guide/jquery/validation-using-jquery-examples.html

Browser other questions tagged

You are not signed in. Login or sign up in order to post.