1st 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 you are going to use form, it is recommended to put all elements sent inside it. Although the same action if using ajax does not need to 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>
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
A [vazio] ("")
resolves, but it could return a NULL, undefined, NaN
, it is always important when running a function test it on several browsers to avoid this type of incident, the same occurs in some cases in IE but not in Firefox, as well as in others.
A tip, valid as numerical and with the number of characters to avoid entering text.
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>