Running the POST before onclick

Asked

Viewed 52 times

0

I’m having a problem, I want before giving Submit to run validation();

    <div class="nova-conta">
    <h2>Cadastre-se</h2>
    <form onsubmit="validarsenha()" method="POST" action="cadastro.php" name="novocadastro"  >
        <div class="form-group">
            <label for="email" class="control-label">E-mail:</label>
            <input type="email" name="f_email" placeholder="Digite seu E-mail" class="form-control" id="email" data-error="Por favor, informe um e-mail correto." required>
        </div>

        <div class="form-group">
            <label for="senha" class="control-label">Senha:</label>
            <input type="password" name="f_senha" placeholder="Digite sua Senha"  class="form-control" id="f_senha" size="20" required>
        </div>
        <div class="form-group">
                <label for="senha" class="control-label">Repita a senha:</label>
                <input type="password" name="f_senhaconfirma" placeholder="Confirme Senha"  class="form-control" id="f_senhaconfirma" size="20"  required>
            </div>
       <div id="btn-conta"> 

        <a href="Index.html" class="btn btn-default"> Cancelar</a>
        <button type="submit" onclick="return validarsenha()" class="btn btn-primary">Cadastrar</button>

       </div>
    </form>

</div>

Remembering what I’m calling this function

function validarsenha(){
var senha=novocadastro.f_senha.value;
var rep_senha=novocadastro.f_senhaconfirma.value;

if(senha == ""  || senha.length < 5){
    alert (`Preencha o campo senha com no minimo 6 caracteres`)
    novocadastro.f_senha.focus();
    return false;
}
if(rep_senha == ""  || rep_senha.length < 5){
    alert (`Preencha o campo confirma senha com no minimo 6 caracteres`)
    novocadastro.f_senhaconfirma.focus();
    return false;
}
if(senha != rep_senha){
    alert (`As senhas sao diferentes!`)
    novocadastro.f_senhaconfirma.focus();
    return false;
}

}

He is always going to PHP, and does not execute the validate function. Anyone knows how I can solve this problem of mine?

  • The code is working... at least in Chrome. The way in which you are capturing the elements of the DOM is depreciated, and has no guarantee that it will work in all browsers. Try to use var senha = document.getElementById('f_senha').value;

  • Put it on the Chrome console to preserve LOG, so try to commit, it is very likely that you have some script error elsewhere/script.

3 answers

0

You can do with js for when the user finishes typing the password he already do this validation. In the example below I have a display message for the user if the passwords are different, and also a variable called Focus that is true if it enters this validation, and in my Submit button only sends if the variable is false, so whenever you enter any validation my form will not submit.

HTML:

<label>Senha</label>
<input class="form-control" type="password" placeholder="********" id="senha_clinica">

<label>Confirmar Senha</label>
<input class="form-control" type="password" placeholder="********"                                     id="senha_confirmacao_clinica">
<span class='error-validacao'>As senhas não coincidem.</span>

jQuery

var focus = false;

 $('#senha_confirmacao_clinica').change(function(){
        //validar se as senhas conferem 
        if($('#senha_confirmacao_clinica').val()!=$('#senha_clinica').val()){
            $('#senha_confirmacao_clinica').css({'border-color': 'red'});
            $('#senha_confirmacao_clinica').parent().find('.error-validacao').css({'display':'block'});
            if ( !focus ) {
                jQuery('#senha_confirmacao_clinica').focus();
                focus = true;
            }
        }
        else{
            $('#senha_confirmacao_clinica').css({'border': '1px solid #ced4da'});
            $('#senha_confirmacao_clinica').parent().find('.error-validacao').css({'display':'none'});
        } 
    });

$('#btn_submit').click(function(){ 
        var envioAjax = false;
        //continuação do ajax de envio...
    });

0

Validation may even occur but the default event of the form is to perform the request. You can use the method preventDefault to cancel the default event and perform the necessary manipulations.

const form = document.querySelector('form[name="novocadastro"]');

form.addEventListener("submit", function(event) {
    event.preventDefault(); //Cancelando o evento padrão

    const validated = validarsenha(); //Executando a função de validação

    if (validated) {
        form.submit(); //Realizando o submit do formulário caso validação esteja correta
    }
});

Now you need to add a true return to the validation function.

function validarsenha() {
    var senha=novocadastro.f_senha.value;
    var rep_senha=novocadastro.f_senhaconfirma.value;

    if (senha == ""  || senha.length < 5) {
        alert('Preencha o campo senha com no minimo 6 caracteres');
        novocadastro.f_senha.focus();
        return false;
    }
    if (rep_senha == ""  || rep_senha.length < 5) {
        alert('Preencha o campo confirma senha com no minimo 6 caracteres');

  novocadastro.f_senhaconfirma.focus();
        return false;
    }
    if (senha != rep_senha) {
        alert('As senhas sao diferentes!');

  novocadastro.f_senhaconfirma.focus();
        return false;
    }

    return true;
}

0

When you click on the Submit button, you are calling a function with onclick and returning false case you enter any if within the function, thus cancelling the effect of Submit. Therefore, the attribute becomes unnecessary onsubmit="validarsenha()" in the form. Validation is already done by onclick button, which, by the way, does not even need type="submit" because the button already is type Submit by default.

Then the form will remain only:

<form method="POST" action="cadastro.php" name="novocadastro">

And the button like this:

<button onclick="return validarsenha()" class="btn btn-primary">Cadastrar</button>

That’s enough to validate the password the way you want it.

Redundancy

Us if'these comparisons of emptiness, for example:

senha == "" || senha.length < 5

It would only be enough senha.length < 5 because if senha == "" already meets the condition senha.length < 5. Then you should just stay:

if(senha.length < 5){

And:

if(rep_senha.length < 5){

Behold:

function validarsenha(event){
   var senha=novocadastro.f_senha.value;
   var rep_senha=novocadastro.f_senhaconfirma.value;
   
   if(senha.length < 5){
       alert (`Preencha o campo senha com no minimo 6 caracteres`)
       novocadastro.f_senha.focus();
       return false;
   }
   if(rep_senha.length < 5){
       alert (`Preencha o campo confirma senha com no minimo 6 caracteres`)
       novocadastro.f_senhaconfirma.focus();
       return false;
   }
   if(senha != rep_senha){
       alert (`As senhas sao diferentes!`)
       novocadastro.f_senhaconfirma.focus();
       return false;
   }
}
<div class="nova-conta">
    <h2>Cadastre-se</h2>
    <form method="POST" action="cadastro.php" name="novocadastro"  >
        <div class="form-group">
            <label for="email" class="control-label">E-mail:</label>
            <input type="email" name="f_email" placeholder="Digite seu E-mail" class="form-control" id="email" data-error="Por favor, informe um e-mail correto." required>
        </div>

        <div class="form-group">
            <label for="senha" class="control-label">Senha:</label>
            <input type="password" name="f_senha" placeholder="Digite sua Senha"  class="form-control" id="f_senha" size="20" required>
        </div>
        <div class="form-group">
                <label for="senha" class="control-label">Repita a senha:</label>
                <input type="password" name="f_senhaconfirma" placeholder="Confirme Senha"  class="form-control" id="f_senhaconfirma" size="20"  required>
            </div>
       <div id="btn-conta"> 

        <a href="Index.html" class="btn btn-default"> Cancelar</a>
        <button type="submit" onclick="return validarsenha()" class="btn btn-primary">Cadastrar</button>

       </div>
    </form>
</div>

Browser other questions tagged

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