How to fix this function, if I type something appears the same thing when I type nothing

Asked

Viewed 290 times

1

<!DOCTYPE html>
<html>
<head>
<title>Atividade 02</title>
<meta charset="utf-8">
</head>
<body>

CPF <font color="red">*</font> <input type="text" name="CPF" id="CPF" size="15" onsubmit="validar(this)">
<form action="tst.html" name="form1" method="post" onsubmit="return validar();">
<input type="submit" value="Cadastrar">
<script language="javascript" type="text/javascript">

function validar () {
    if (validar=="") {
        alert("Todos os campos foram preenchidos.");
        return true;
} else {
        alert("*Campo obrigatório")
        return false;
}
}
</script>
</body>
</html>

3 answers

2

Opa, if you just want to force the user to enter something in the field you can use required in the field you want it to be mandatory, when he try to submit the form appears the mandatory message:

<!DOCTYPE html>
<html>
    <head>
        <title>Atividade 02</title>
        <meta charset="utf-8">
    </head>
    <body>
        <form action="tst.html" name="form1" method="post">
            CPF <font color="red">*</font> <input type="text" name="CPF" id="CPF" size="15"required>
            <input type="submit" value="Cadastrar">
        </form>
    </body>
</html>

Note: always put your fields inside the form as above.

If you want to validate with Javascript you can do so:

<!DOCTYPE html>
<html>
    <head>
        <title>Atividade 02</title>
        <meta charset="utf-8">
        <script>
            function validar(event)
            {
                var cpf = document.getElementById("CPF").value;
                if(cpf === "")
                {
                    event.preventDefault();
                    alert("Campo obrigatório");
                }
                else {
                    alert("Tudo certo!");
                }
            }
        </script>
    </head>
    <body>
        <form action="tst.html" name="form1" method="post" onsubmit="validar(event);">
            CPF <font color="red">*</font> <input type="text" name="CPF" id="CPF" size="15">
            <input type="submit" value="Cadastrar">
        </form>
    </body>
</html>

event.preventDefault(); will prevent the form from being submitted;

var cpf = document.getElementById("CPF").value; takes the value that is in the Cpf field and below compares whether it is empty or not.

To compare strings here use === and not == (for a concrete explanation of this, look at this question and the answers).

I hope to have contributed, until.

1

As it turned out:

<!DOCTYPE html>
<html>
<head>
<title>Atividade 02</title>
<meta charset="utf-8">
</head>
<body>
<form name="form1" id="form1" method="POST">
CPF: <font color="red">*</font><input type="text" name="CPF" id="CPF" size="15">
<input type="button" value="Cadastrar" onclick="beforeSubmit();">
</form>
</body>
<script type="text/javascript">
function beforeSubmit(){
    var cpf = document.getElementById('CPF').value;
    if (cpf != "") {
        alert("Todos os campos foram preenchidos.");
        return true;
    } else {
        alert("*Campo obrigatório")
        return false;
    }
   document.getElementById('form1').submit();
}
</script>
</html>

Any doubt just call, hope it helped. Good studies.

1

first onsubmit is in the form, not the object, there are several ways to send the data of an element, when there is no more than one element with the same name, called by nomeobjeto.value is more efficient than putting getElementById, getElementByName, getElementByTagName.

2nd When using form, it is recommended to place all sent elements within it. Although the same action if using ajax does not need form.

<!DOCTYPE html>
<html>
<head>
<title>Atividade 02</title>
<meta charset="utf-8">
</head>
<body>

CPF <font color="red">*</font>
<form action="tst.html" name="form1" method="post" onsubmit="return validar(CPF.value);">
<input type="text" name="CPF" id="CPF" size="15">
<input type="submit" value="Cadastrar">
<script language="javascript" type="text/javascript">

function validar (valida) {
    if (valida!="") {
        alert("Todos os campos foram preenchidos.");
        return true;
} else {
        alert("*Campo obrigatório")
        return false;
}
}
</script>
</body>
</html>

Obs.: Above is the same code with the syntax correction, preserving its syntax, it is worth noting that both objects and variables, can return other types of output when empty, in the example above a [vazio] ("") resolves, but he could return a NULL, undefined, NaN, is always important when running a function test it on multiple browsers to avoid this type of incident, the same occurs in some cases in IE, but not in Firefox, as in others.

A hint, validate as numeric and with the number of characters to avoid text input.

CPF <font color="red">*</font>
<form action="tst.html" name="form1" method="post" onsubmit="return validar(CPF.value);">
<input type="text" name="CPF" id="CPF" size="15">
    <input type="submit" value="Cadastrar"/>
<script>
    function validar (valida) {
    if (valida.replace(/[^0-9]/g,'')!="" && valida.replace(/[^0-9]/g,'').length==11) {
        alert("Todos os campos foram preenchidos.");
        return true;
} else {
        alert("*Campo obrigatório")
        return false;
}
}
</script>
  • The regular expression [^0-9] removes text, allowing only number when validating, and the attribute length counts the number of characters, whenever validating items apply the length outside of validation.

  • I put an example of validation of more than one http://jsfiddle.net/gf22aaLcfield/

Browser other questions tagged

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