How to validate a form with a specific number os caracteres

Viewed 80

I am trying to build a code that validate a form. When the user types in the 'cpf' form the code must know if he typed numbers and if he typed exactly 11 numbers. Something went wrong in this code and I do not know what it is. When I type in the form it will always return "please match the requested format". It does not matter if I typed words, numbers, or 11 numbers or just one or two. This is an exercise I am working into because I am learning about JavaScript and this is my first time working with this language. Anyway, I believe I have to add something that turn the information in the form into a string or and them I can count the length of this string (??). I do not know how to do that in that code. Any tips or corrections?

<!DOCTYPE html>
<html>
<body>

<h1 style="font-size:50px; color:blue; text-align:center; border: 2px solid Tomato">Cadastro de produto</h1>

<div>
  <form name="form1" style="text-align:center" action="/action_page.php">
    CPF:
    <br>
    <input type="text" id="cpf" name="cpf" maxlength="11" pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}" title="Digite apenas os 11 numeros que compõem seu CPF" required>
    <br><br>
    Nome completo:
    <br>
    <input type="text" id="nome" name="nome" pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}" title="Digte aqui o seu nome completo" required>
    <br><br>
    E-mail:
    <br>
    <input type="text" id="email" name="email" pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}" title="Digte aqui o seu E-mail" required>
    <br><br>
    Mensagem:
    <br><br>
    <textarea name="message" rows="10" cols="80"></textarea>
    <br>
    <input type="submit" value="Salvar">
  </form>
</div>

<div id="reqs">
  <p id="cpff" class="invalid"></p>
  <p id="emaill" class="invalid"></p>
</div>

<script>

    var cpfInput = document.getElementById("cpf");
    var cpfInput = cpfInput.toString();
    var cpff = document.getElementById("cpff")

    // Esconde o paragrafo 'reqs' quando o usuário clicar em qualquer campo fora do formulário
    cpfInput.onblur = function() {
    document.getElementById("reqs").style.display = "none";
    }

    cpfInput.onkeyup = function() { 

      // Valida o campo cpf
      var inputCPF = /[0-9]/g;

      if(cpfInput.value.match(inputCPF)) {  
        cpff.classList.remove("invalid");
        cpff.classList.add("valid");
      }
      else {
        cpff.classList.remove("valid");
        cpff.classList.add("invalid");
      }

      // Valida a quantidade de caracteres no campo CPF
      if(cpfInput.value.length == 11) {
        cpff.classList.remove("invalid");
        cpff.classList.add("valid");
      }
      else {
        cpff.classList.remove("valid");
        cpff.classList.add("invalid");
      }
    }

</script>

</body>
</html>
3 Answers

First, you don't need to convert your DOM element to string here:

// You don't need this!
var cpfInput = cpfInput.toString();

Second, use different RegEx pattern to match 11 characters - /[0-9]{11}/g. In this case you don't need to check the length of string afterwards. The complete onkeyup function can be like this:

cpfInput.onkeyup = function() { 
  // Valida o campo cpf
  var inputCPF = /[0-9]{11}/g;

  if(cpfInput.value.match(inputCPF)) {  
    cpff.classList.remove("invalid");
    cpff.classList.add("valid");
  }
  else {
    cpff.classList.remove("valid");
    cpff.classList.add("invalid");
  }
}

If you're validating your "CPF" format with javascript, there's no need to include the "pattern" attribute in your DOM. In case you decide to use the "pattern" attribute in your DOM, use it correctly -- the regex you put in all inputs mean: "must contain 8 or more characters that are of at least one number, and one uppercase and lowercase letter". This usually fits for password only

Check w3schools for further reference.

P.s. you're declaring "cpfInput" variable twice.

Your cpf field has a regex pattern validation on it that appears to have been copy-pasted from somewhere else ((?=.\d)(?=.[a-z])(?=.*[A-Z]).{8,}). You should remove it or replace it with the pattern you actually want to validate against, which should be:

/[0-9]{11}/
Related