Usamos cookies para medir audiência e melhorar sua experiência. Você pode aceitar ou recusar a qualquer momento. Veja sobre o iMasters.
Pessoal, bom dia.
Estou tentando criar uma validação via PHP, não usando Java Script para validar uma data. Não deixar uma pessoa cadastrar como data de nascimento uma data maior que a data atual. Tentei os seguintes códigos, mas não funciona.
Campo do arquivo dados_iniciais.php:
<td><label for="dt_nascimento"><input name="dt_nascimento" id="dt_nascimento" type="text" maxlength="10" size="10" value="<?=ValidaData($cr_dt_nascimento,$dt_nascimento);?>" ></label></td>
Função ValidaData do arquivo funcoes.php
function ValidaData($theValue,$name){
$data_atual=date("d/m/Y");
if($theValue>$data_atual){
echo "<script language='javascript'>
window.alert('Data maior que a data atual!');
document.getDocumentById('".$name."').focus();
</script>";
}else{
return $theValue;
}
}
Abaixo os códigos completos:
dados_iniciais.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="[http://www.w3.org/1999/xhtml"](http://www.w3.org/1999/xhtml) lang="pt-br">
<head>
<title>Procurando Minha Família - Dados Iniciais</title>
<meta http-equiv="Content-Type" content="text/html"; charset="iso-8859-1">
<script language="javascript">function SubmitVoltar(cr_id_num)
{crianca_id=cr_id_num;
document.f.action='alterar_crianca.php?id_crianca';
document.f.method='post';
document.f.submit();
}
<!--A função abaixo realiza a validação dos campos do formulário "inicial" -->
function enableFields()
{//var totalFields = document.f.elements.length;
if(document.f.valida_data.value==1){
//for (i = 1; i < totalFields; i++) {
document.f.dt_nascimento.disabled = false;
document.f.idade.disabled = false;
document.f.idade_pres.disabled = true;
}else{
document.f.dt_nascimento.disabled = true;
document.f.idade.disabled = true;
document.f.idade_pres.disabled = false;
}
}
function validaform() var validadesaparecido= /^[a-z A-Z]{2,50}$/;
var vdatavalida=/^\d{1,2}\/\d{1,2}\/\d{1,4}$/;
var vdatanasc=/^\d{1,2}\/\d{1,2}\/\d{1,4}$/;
if(document.f.desaparecido.value.search(validadesaparecido)==-1){
alert("Digite somente caractere alfabético!!!");
document.f.desaparecido.focus();
}
else if(document.f.sexo.selectedIndex==0){
alert("Entre com um sexo válido!!!");
document.f.sexo.focus();
}
else if(document.f.valida_data.selectedIndex==0){
alert("Escolha entre as duas opções");
document.f.valida_data.focus();
}
else if((document.f.valida_data.selectedIndex==2)&& (document.f.idade_pres.value=="")){
alert("Entre com uma idade presumida");
document.f.dt_nascimento.value="";
document.f.idade_pres.focus();
}
else if((document.f.valida_data.selectedIndex==1)&&(document.f.dt_nascimento.value.search(vdatanasc)==-1)){
alert("Informe tipo da data de nascimento");
document.f.dt_nascimento.focus();
document.f.idade_pres.value="";
}
/*else if(document.f.data_valida.value.search(vdatavalida)=-1){
alert("Entre com uma data válida no formato dd/mm/aaaa");
f.data_valida.focus();
}*/
else{
SubmitAlteracao();
}
function SubmitAlteracao()
{
document.f.action='update_crianca.php';
document.f.method='post';
document.f.submit();
}
}
</script>
<!-- link para a folha de estilo-->
<link href="../css/epg.css" rel="stylesheet" type="text/css">
</head>
<!--Seta o foco para o campo Nome do desaparecido-->
<body onLoad="javascript:document.f.desaparecido.focus(); javascipt:enableFields();">
<?php
//chama a tela de autenticação
include "../includes/autenticarlogin.php";
include "../conexao/conexao_total.php";
include '../autentica/crianca.php';
include "../funcoes/funcoes.php";
//setando as variáveis
$data_login=date("Y-m-d H:i:s");
$id_oper = $_SESSION['CR_COD_OPERADOR_LOG'];
$id = $_POST['crianca_id'];
//consultando a tabela crianca
$result = "SELECT CR_NOME_CRIANCA, CR_NOME_SUGERIDO, CR_APELIDO, CR_SEXO, CR_VALIDA_DATA, CR_DT_NASCIMENTO, CR_IDADE_PRESUMIVEL, CR_NUM_IDENTIDADE, CR_ORGAO_EMISSOR FROM crianca WHERE CR_ID_NUM = '$id'";
$query = mysql_query($result) or die('Erro ao consultar no banco de dados !!!');
$lista=mysql_fetch_assoc($query);
$cr_nome_crianca=$lista["CR_NOME_CRIANCA"];
$cr_nome_sugerido=$lista["CR_NOME_SUGERIDO"];
$cr_apelido=$lista["CR_APELIDO"];
$cr_sexo=$lista["CR_SEXO"];
$cr_valida_data=$lista["CR_VALIDA_DATA"];
$cr_dt_nascimento=$lista['CR_DT_NASCIMENTO'];
$cr_idade_presumivel=$lista["CR_IDADE_PRESUMIVEL"];
$cr_num_identidade=$lista["CR_NUM_IDENTIDADE"];
$cr_orgao_emissor=$lista["CR_ORGAO_EMISSOR"];
?>
<form name="f" method="post">
<table align="center" width="70%" border="0" cellspacing="1" cellpadding="0" class="texto">
<tr><td colspan="2"><br /></td></tr>
<tr>
<td colspan="2" align="center" class="texto"><strong>Dados Iniciais</strong></td>
</tr>
<tr><td><br /></td></tr>
<tr>
<td><label for="desaparecido">Nome Criança / Adolescente Dedaparecido</label></td>
</tr>
<tr>
<td><input id="desaparecido" name="desaparecido" type="text" value="<?=$cr_nome_crianca?>" size="50" maxlength="45"> </td>
</tr>
<tr>
<td><label for="nome_sug">Nome Sugerido</label></td>
</tr>
<td><input type="text" id="nome_sug" name="nome_sug" value="<?=$cr_nome_sugerido?>" size="50" maxlength="45"> </td>
</tr>
<tr>
<td><label for="apelido">Apelido</label></td>
<td><label for="sexo">Sexo</label></td>
</tr>
<tr><td><input type="text" name="apelido" id="apelido" value="<?=$cr_apelido?>" size="45" maxlength="40"></td>
<td><select name="sexo" id="sexo">
<?php
if($cr_sexo==NULL)
{
print("<option value='' selected>Escolha uma opção</option>
<option value='M'>Masculino</option>
<option value='F'>Feminino</option>");
}
else if($cr_sexo=="M"){
print("<option value=''>Escolha uma opção</option>
<option value='M'selected>Masculino</option>
<option value='F'>Feminino</option>");
}
else{
print("<option value=''>Escolha uma opção</option>
<option value='M'>Masculino</option>
<option value='F' selected>Feminino</option>");
}
?>
</select></td>
</tr>
<tr>
<td>Nascimento</td>
<td><label for="valida_data">Data de Nascimento</label></td>
<td><label for="idade">Idade</label></td>
</tr>
<td><select name="valida_data" id="valida_data" onchange="enableFields();">
<?php
if($cr_valida_data==NULL)
{
print("<option value='0' selected>Escolha uma opção</option>
<option value=1>Data Valida</option>
<option value=2>Data Presumida</option>");
}
else if($cr_valida_data==1)
{
print("<option value='0'>Escolha uma opção</option>
<option value=1 selected>Data Valida</option>
<option value=2>Data Presumida</option>");
}
else{
print("<option value='0'>Escolha uma opção</option>
<option value=1>Data Valida</option>
<option value=2 selected>Data Presumida</option>");
}
?>
</select> </td>
<?php $dt_nascimento="dt_nascimento";?>
<td><label for="dt_nascimento"><input name="dt_nascimento" id="dt_nascimento" type="text" maxlength="10" size="10" value="<?=ValidaData($cr_dt_nascimento,$dt_nascimento);?>" ></label></td>
<?php
function calc_idade( $cr_dt_nascimento ){
$data_nasc=explode("/",$cr_dt_nascimento);
$data=date("d/m/Y");
$data=explode("/",$data);
$anos=$data[2]-$data_nasc[2];
if($cr_dt_nascimento==""){
$anos="";
return $anos;if ($data_nasc[1] > $data[1]) {
return $anos-1;
} if ($data_nasc[1] == $data[1]) {
if ($data_nasc[0] <= $data[0]) {
return $anos;
break;return $anos-1;
break;
}
} if ($data_nasc[1] < $data[1]) {
return $anos;
}
}
?>
<?php $anos = calc_idade($cr_dt_nascimento);?>
<td><input type="text" name="idade" value="<? echo $anos;?>" size="5" maxlength="2" readonly="true"></td>
</tr>
<tr>
<td><label for="idade_pres">Idade Presumida</label></td>
</tr>
<tr>
<td><input name="idade_pres" type="text" value="<?=$cr_idade_presumivel?>" size="5" maxlength="2"></td>
</tr>
<tr>
<td><label for="identidade">Nº Identidade</label></td>
<td><label for="orgao_em">Órgão Emissor</label></td>
</tr>
<tr>
<td><input type="text" name="identidade" value="<? echo $cr_num_identidade; ?>" /></td>
<td><input type="text" name="orgao_em" value="<?=$cr_orgao_emissor?>"></td>
</tr>
</table>
<table align="center" width="80%" border="0" cellspacing="1" cellpadding="0" class="text">
<tr><td></td></tr>
<tr>
<td colspan="2" align="center">
<input name="update" type="button" class="bt" onClick="javascript:validaform()" value="Atualizar">
<input name="volta" type="button" class="bt" onclick="javascript:SubmitVoltar(<? echo $id; ?>)" value=" Voltar" />
<input type="hidden" name="id_crianca" value="<? echo $id; ?>" /> </td>
</tr>
<tr>
<td colspan="2" align="center"> </td>
</tr>
</table>
<p> </p>
</form>
<? include '../includes/rodape.html'; ?>
</body>
</html>
funcoes.php
<?php
function FormataDataAmericana($theValue) {
$fdia = substr($theValue,0,2);
$fmes = substr($theValue,3,2);
$fano = substr($theValue,6,4);
return $fano."/".$fmes."/".$fdia;
}
// para trabalhar com o calendar ------
function FormataDataBrasil($theValue) {
$fano = substr($theValue,0,4);
$fmes = substr($theValue,5,2);
$fdia = substr($theValue,8,2);
return $fdia."-".$fmes."-".$fano;
}
//-------------------------------------
function FormataDataBrasil2($theValue) {
$fano = substr($theValue,0,4);
$fmes = substr($theValue,5,2);
$fdia = substr($theValue,8,2);
return $fdia."/".$fmes."/".$fano;
}
function FormataDataMysql($theValue) {
$fdia = substr($theValue,0,2);
$fmes = substr($theValue,3,2);
$fano = substr($theValue,6,4);
$data_con=array($fano,$fmes,$fdia);
$data=implode("-",$data_con);
return $data;
}
//----------------------------------
function FormataCPF($theValue) {
$f1 = substr($theValue,0,3);
$f2 = substr($theValue,3,3);
$f3 = substr($theValue,6,3);
$f4 = substr($theValue,9,2);
return $f1.".".$f2.".".$f3."-".$f4;
}
function FormataCEP($theValue) {
$f1 = substr($theValue,0,5);
$f2 = substr($theValue,5,3);
return $f1."-".$f2;
}
function FormataNumeroAmericano($theValue) {
return str_replace(array(","), ".", $theValue);
}
function FormataNumeroBrasil($theValue) {
return str_replace(array("."), ",", $theValue);
}
function FormataProcesso($theValue) {
$f1 = substr($theValue,0,4);
$f2 = substr($theValue,4,3);
$f3 = substr($theValue,8,6);
$f4 = substr($theValue,14,1);
return $f1.".".$f2.".".$f3."-".$f4;
}
function FormataIdentidade($theValue){
$f1=substr($theValue,0,2);
$f2=substr($theValue,2,3);
$f3=substr($theValue,5,3);
$f4=substr($theValue,8);
return $f1 .".".$f2.".".$f3."-".$f4;
}
function ValidaData($theValue,$name){
$data_atual=date("d/m/Y");
if($theValue>$data_atual){
echo "<script language='javascript'>
window.alert('Data maior que a data atual!');
document.getDocumentById('".$name."').focus();
</script>";
}else{
return $theValue;
}
}
?>Carregando comentários...