Function calling other functions

Asked

Viewed 168 times

3

I have a form and 1 function to validate each field of this form

function valida_nome() {
		
}
	
function valida_email() {
		
}
	
function valida_tel() {
		
}
	
function valida_senha() {

}
	
<form id="usuario_form" name="usuarios_form" method="POST" action="#">
    <input type="text" id="input_nome_cad" class="input nome_cad" name="nome_cad" placeholder="Nome e Sobrenome"   onblur="valida_nome(this)">
    <br/>

    <input type="text" id="input_email_cad"class="input email_cad"name="email_cad"   	placeholder="Insira o Email"     onblur="valida_email(this)">
    <br/>

    <input type="text" id="input_conf_email_cad"class="input conf_email_cad"name="conf_email_cad"  placeholder="Confirme seu email" ><br/>
    <input type="text" id="input_tel_cad"	class="input tel_cad" name="tel_cad"     	placeholder="Insira um telefone"><br/>
    <input type="text"id="input_conf_tel_cad"	class="input tel_cad" name="conf_tel_cad"    placeholder="Confirme o telefone">
    <br/>

    <input type="password" id="input_senha_cad"class="input senha_cad"	 	 name="senha_cad"   	placeholder="Insira uma senha"><br/>
    <input type="password" id="input_conf_senha_cad" class="input senha_cad"	 	 name="conf_senha_cad"  placeholder="Confirme a senha">
    <input type="submit" 	class="btn_enviar_cad"	 name="enviar_cad"  value="Criar Conta" onclick="return valida_form(this)">
</form>

I would like a function from an event onload, performing all four functions, that is to say a function valida_form that would perform the functions valida_nome, valida_email, valida_tel, valida_senha.

Questions:

  • Where is the place and how to proceed in the onload?
  • Nesting functions in javascript, if this term is correct?
  • Were the answers below helpful? Were you able to solve the problem?

3 answers

4


Creates an object with these functions. In the element joins a field data- with the name of the function you must perform and you get functional code and easy to understand.

For example:

In HTML:

<input type="text" id="input_nome_cad" data-regra="valida_nome" ...etc
                                       ^----------------------^

And then in Javascript:

var regras = {
    valida_nome: function() {

    },
    valida_email: function() {

    },
    valida_tel: function() {

    },
    valida_senha: function() {

    }
}

var form = document.getElementById('usuario_form');
var enviar = document.querySelector('.btn_enviar_cad');
var inputs = [].slice.call(document.querySelectorAll('.input')); // para criar uma array
enviar.addEventListener('click', function(e) {
    e.preventDefault(); // para não enviar ainda
    var validos = inputs.filter(function(el) {
        var fn = el.dataset.regra;
        var valido = regras[fn](el); // aqui vai validar o input e retorna true se validar correto
        // aqui podes fazer algum aviso caso valido != true
        return valido;
    });
    if (validos.length == input.length) form.submit(); // todos são válidos!
})
  • 1

    well played "element joins a field data- with the function name.."

1

You can place the validation at the moment the user tries to submit the data from form, then you do all the validation and if you have any error, just stop the data from being sent:

<form id="usuario_form" name="usuarios_form" method="POST" onsubmit="return validaForm()" action="#">
...
</form>

<script>
    function ID(id) {
        return document.getElementById(id);
    }

    function validaForm() {
        if(validaNome() && validaEmail() && validaTel() && validaSenha()) {
            return true;
        }

        return false;
    }

    function validaNome() {
        var nome = ID('input_nome_cad');

        if(nome.value == '')
            return false;

        return true;
    }

    function validaEmail() {
        // ...
    }

    function validaTel() {
        // ...
    }

    function validaSenha() {
        // ...
    }

</script>

I hope I helped the/

  • in this case I would like to validate the field itself, type the pg opens and already gives a "Focus()" in the 1st field and already does the validation and does not allow to advance to the next field while the conditions are not met, I ended up doing 1 function only and each validation is a block... But see the man...

  • In that case, I suggest you use jQuery to do this kind of validation. Then you can manipulate the fields more easily $('input_nome_cad').on('change', function() { if (this.value == '') alert('preencha este campo');});

  • mass but I’m still learning, doing everything kind of procedural, later I give a tibum in the classes and libraries, now no chance, o tico e teco já tão sair na mão aqui com javascript e php, imagine bota o jquery... ainda num dá para mim...vlw a força man

  • Ball show, welcome to the world of programming. If you have familiarity with English, I suggest you read the tutorials of W3schools for JavaScript and after jQuery. Good studies the/

0

If what you want to do is a user input validation (and you don’t need to make ajax calls or more complicated things) you can just use patterns and the type HTML already gives you:

<input type="email" />
<input type="number" min="0" max="1"/>

you can also use the type=text allied with the pattern:

<input type="text" pattern="/[a-z_]/g" placeholder="just lower case letters and underscores" />

and you can also use the pattern with all other input types

<input type="email" pattern="/gmail.com$/" placeholder="we only accept gmail accounts" />

When you click on submit if something fails, natively will stop the form Submit.

In the case of JS, you can use the onchange,

document.querySelector('#id,.classe,element').onchange(function(){});

or

<input id="id" type="email" onchange="return validar_email(event);"/>
  • actually I’m doing a validation , but the requirement is pure js, without Html5 or other , is my doubt is about the nesting functions, but I appreciate the attention, good day.....

  • 1

    @Magichat in this case you can use the onchange,

  • It was the solution I used... VLW

Browser other questions tagged

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