Password validation with javascript

Asked

Viewed 165 times

-2

I am trying to validate a form, which it from Submit in the form only if the password field is filled with at least 1 UPPERCASE LETTER, 1 NUMBER, 1 MINUSCULE LETTER. I did this with regex Pattern but, if you click again on the Submit button it sends the form. I wanted the form to send only if the password is typed this way, and if it is not returning the error message not as an Alert, but within a div.

<input autocomplete="off" type="password"  class="form-control" pattern="(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=^.{8,50}$).*$" onchange="if(!this.validity.valid)alert('Senha Inválida!')" id="password" name="password" placeholder="Digite sua senha" required/>

<button type="submit" name="botaologin" id="botaologin">Entrar</button>
  • Put your entire form code here... will make it easier for the staff to help you.

1 answer

0

There are some ways to do this.

I usually do it using javascript for both validation and form submission (using Ajax). So I have absolute control of which moment I can send the form and also which return I will get after sending and processing the server.

Another advantage is that it is not necessary to load the page and this improves the user experience.

Remembering that it is also important that this password validation is done on the server.

Here’s an example of the way I usually do form Ubmit:

HTML:

<form id="meuForm" action="">

  <label>Senha: </label>
  <input id="senha" type="text" name="senha"/>

  <button type="submit" id="botaoSubmit"></button>
  
  
</form>

In Javascript you can use Ajax the way you prefer, I do with Fetch API:

Javascript

document.querySelector('#meuForm').addEventListener('submit', function(e){
    
  // Isso impede que o form seja enviado ao clicar no botão de envio do formulário
  e.preventDefault();
    
  // Aqui você pode recuperar a senha e verificar se a mesma está no formato desejado
  let senha = document.querySelector('#senha').value;
  let senhaValida = VerificaSenha(senha);
    
  if(senhaValida == true){
    EnviaForm(senha); 
    
  } else {
    // Aqui vai o trecho de código para exibir a mensagem de erro em uma DIV
  }    
  
});


function EnviaForm(senha){

fetch(`suaUrl`, optionsPost = { method: "POST", mode: "cors", body: senha })
        .then(response => {
            response.json()
                .then(data => {                    
                    // Deu certo o envio
                    console.log(data);

                })
                .catch();
        })
        .catch(error => {
            // Se o server apresentar erro em qualquer ação cairá aqui
            console.log("Erro: " + error);
        });
}

This way, all validation is controlled by javascript before sending the form to the server.

  • It didn’t work No, you’re making a mistake.

  • What error? Be more specific and if possible show with images and examples so I can help you.

Browser other questions tagged

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