0

Im new to php and trying to validate some fields in the user form using javascript. The problme is sometimes it works and sometimes dont, and when the alert disappears all the fields that the user was alreay filled, is blank again.

Heres my php code :

<script>
            function validar(formulario){
                if(formulario.nome.value == ''){
                    alert("O campo NOME é obrigatório.");
                    return false;
                }
                if(formulario.Email.value == ''){
                    alert("O campo EMAIL é obrigatório.");
                    return false;
                }
                if(formulario.Email.value.indexOf(('@' && '.'),0)== -1){
                    alert("EMAIL invalido.");
                    return false;
                }
                if(formulario.usuario.value == ''){
                    alert("O campo USUÁRIO é obrigatório.");
                    return false;
                }
                if(formulario.senha.value == ''){
                    alert("O campo SENHA é obrigatório.");
                    return false;
                }
                if(formulario.uf.value.length > 3 || formulario.uf.length <=1){
                    alert("O campo UF é inválido.");
                    return false;
                }
                if(formulario.crm.value.length < 4){
                    alert("O número do CRM é inválido.");
                    return false;
                }
                if(formulario.cidade.value.value == ''){
                    alert("O número do CRM é inválido.");
                    return false;
                }
                return true;
            }
        </script>
</head>
<body>

<form id="formulario" method="post" onsubmit="return validar(this);" action="cadastrar.php">
 <B>Nome: </B><input type=text name=nome size="50"> <br>
<BR>
<B>E-mail: </B><input type=text name=Email size="50"><br>
<BR>
<B>Nome de Usuário: </B><input type=text name=usuario size="50"><br>
<BR>
<B>Senha: </B><input type=text name=senha size="10"><br>
<BR>
<B>CRM: </B><input type=text name=crm size="5"><br>
<BR>
<B>UF: </B><input type=text name=uf size="2"><br>
<BR>
<B>Cidade: </B><input type=text name=cidade size="20"><br>
<BR>
<B>Especialidade Médica: </B><input type=text name=esp size="30"><br>
<BR>

<input type="submit" name="Submit" value="Enviar" /> <br />

</form>
7
  • 1
    Can you provide data that works and data that doesn't? Commented Sep 16, 2012 at 16:01
  • For example the field "senha" never works Commented Sep 16, 2012 at 16:02
  • 1
    -1 for being lazy when writing code ! use " always, like value="name" Commented Sep 16, 2012 at 16:04
  • 2
    .indexOf(('@' && '.'),0) is the same as .indexOf('.',0) because ('@' && '.') evaluates to '.'. Commented Sep 16, 2012 at 16:05
  • 1
    and also, <input type=text name=uf size="2"> write it like <input type="text" name="uf" size="2" />, using /> at end; write valid code ! Commented Sep 16, 2012 at 16:06

3 Answers 3

1

Try cleaning up your code:

<script type="text/javascript">
    function validar(formulario) {
        var nome = formulario.nome.value;
        if (nome == '') {
            alert("O campo NOME é obrigatório.");
            return false;
        }
        var email = formulario.Email.value;
        if (email == '') {
            alert("O campo EMAIL é obrigatório.");
            return false;
        }
        if (email.indexOf('@') < 0 || email.indexOf('.') < 0) {
            alert("EMAIL invalido.");
            return false;
        }
        var usuario = formulario.usuario.value;
        if (usuario == '') {
            alert("O campo USUÁRIO é obrigatório.");
            return false;
        }
        var senha = formulario.senha.value;
        if(senha == '') {
            alert("O campo SENHA é obrigatório.");
            return false;
        }
        var uf = formulario.uf.value;
        if (uf.length > 3 || uf.length <= 1) {
            alert("O campo UF é inválido.");
            return false;
        }
        var crm = formulario.crm.value;
        if (crm.length < 4) {
            alert("O número do CRM é inválido.");
            return false;
        }
        var cidade = formulario.cidade.value;
        if (cidade == '') {
            alert("O número do CRM é inválido.");
            return false;
        }
        return true;
    }
</script>
</head>
<body>

<form id="formulario" method="post" onsubmit="return validar(this);" action="cadastrar.php">
    <b>Nome: </b><input type="text" name="nome" size="50" /><br/><br/>
    <b>E-mail: </b><input type="text" name="Email" size="50" /><br/><br/>
    <b>Nome de Usuário: </b><input type="text" name="usuario" size="50" /><br/><br/>
    <b>Senha: </b><input type="text" name="senha" size="10"><br/><br/>
    <b>CRM: </b><input type="text" name="crm" size="5"><br/><br/>
    <b>UF: </b><input type="text" name="uf" size="2"><br/><br/>
    <b>Cidade: </b><input type="text" name="cidade" size="20"/><br/><br/>
    <b>Especialidade Médica: </b><input type="text" name="esp" size="30"/><br/><br/>
    <input type="submit" name="Submit" value="Enviar" /><br />
</form>
Sign up to request clarification or add additional context in comments.

Comments

0

Sloppy coding

this will work better DEMO

function validar(formulario){
  if(formulario.nome.value == ''){
    alert("O campo NOME é obrigatório.");
    return false;
  }
  if(formulario.Email.value == ''){
    alert("O campo EMAIL é obrigatório.");
    return false;
  }
  if(formulario.Email.value.indexOf(('@' && '.'),0)== -1){
    alert("EMAIL invalido.");
    return false;
  }
  if(formulario.usuario.value == ''){
    alert("O campo USUÁRIO é obrigatório.");
    return false;
  }
  if(formulario.senha.value == ''){
    alert("O campo SENHA é obrigatório.");
    return false;
  }
  if(formulario.crm.value.length < 4){
    alert("O número do CRM é inválido.");
    return false;
  }
  if(formulario.uf.value.length > 3 || formulario.uf.length <=1){
    alert("O campo UF é inválido.");
    return false;
  }
  if(formulario.cidade.value == ''){
    alert("O número do cidade é inválido.");
    return false;
  }
  return true;
}​

I also suggest adding

function isEmail(str) { // http://stackoverflow.com/a/4964763/295783
  return /(.+)@(.+){2,}\.(.+){2,}/.test(str);
}

and have

if(!isEmail(formulario.Email.value)){
  alert("EMAIL invalido.");
  return false;
}

Comments

0

Rewrote script to make easily extendible

function validar(formulario){
    var checkEmptyString = function(x){
            return x === undefined || x === null || x === '';
        },
        minLen = function(s, i){
            return s.length >= i;
        },
        maxLen = function(s, i){
            return s.length <= i;
        },
        betweenLen = function(s, min, max){
            return s.length >= min && s.length <= max;
        },
        containsChars = function(s, chars){
            var i = 0;
            for( i=0; i<chars.length; i++ ) if(s.indexOf(chars[i]) === -1) return false;
            return true;
        },
        testEmpty = ['nome', 'Email', 'usuario', 'senha', 'cidade'],
        testContain = {'Email': '@.'},
        testMin = {},
        testMax = {'crm':4},
        testBetween = {'uf':[2, 3]},
        i = 0;
    for( i=0; i<testEmpty.length; i++){
        if( checkEmptyString( formulario[ testEmpty[i] ].value ) )
            return alert('O campo '+testEmpty[i].toUpperCase()+' é obrigatório.'),
                   false;
    }
    for( i in testContain ){
        if( false === containsChars( formulario[ i ].value, testContain[i] ) )
            return alert(i.toUpperCase()+' invalido.'),
                   false;
    }
    for( i in testMin ){
        if( false === minLen( formulario[ i ].value, testMin[i] ) )
            return alert('O número do '+i.toUpperCase()+' é invalido.'),
                   false;
    }
    for( i in testMax ){
        if( false === maxLen( formulario[ i ].value, testMax[i] ) )
            return alert('O número do '+i.toUpperCase()+' é invalido.'),
                   false;
    }
    for( i in testBetween ){
        if( false === betweenLen( formulario[ i ].value, testBetween[i][0], testBetween[i][1] ) )
            return alert('O campo '+i.toUpperCase()+' é invalido.'),
                   false;
    }
    return true;
}

I know this response was a bit late

3 Comments

Also way to complicated for a newbie to change.
I'll give you that I didn't comment it to point it out, but calling adding items to objects/arrays which already have examples you can copy&paste too complicated?
Ahem... Try adding a dropdown or checkbox or change the message to not use the field name - not straight forward for a newbie :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.