sEnte Posted July 27, 2012 Report Share Posted July 27, 2012 Boas pessoal tudo bem? Num formulário que aqui tenho quero juntar o env io de um número de telefone (móvel ou fixo) mas estou com dificuldades em fazer isso. será que podem dar-me uma ajuda? com os melhores cumprimentos "If It Ain't Broke, Break it and build something Cooler!" Unknown Link to comment Share on other sites More sharing options...
HappyHippyHippo Posted July 27, 2012 Report Share Posted July 27, 2012 pretendes validar antes do envio do formulário através de javascript ou após a recepção do formulário no servidor com PHP ? IRC : sim, é algo que ainda existe >> #p@p Portugol Plus Link to comment Share on other sites More sharing options...
sEnte Posted July 27, 2012 Author Report Share Posted July 27, 2012 no envio do número. até ver tenho estado a fazer tudo em PHP. mas pode ser com javascript também. se não for complicado dá para arranjar os 2? "If It Ain't Broke, Break it and build something Cooler!" Unknown Link to comment Share on other sites More sharing options...
HappyHippyHippo Posted July 27, 2012 Report Share Posted July 27, 2012 usas jquery ? IRC : sim, é algo que ainda existe >> #p@p Portugol Plus Link to comment Share on other sites More sharing options...
sEnte Posted July 27, 2012 Author Report Share Posted July 27, 2012 (edited) agora estou a usar um jquery validate que encontrei na net. o que queria fazer realmente era mais ou menos isto... Verificar se o campo referente ao número estava preenchido. Caso não estivesse preenchido o script corria normalmente e não enviava número nenhum. se tivesse alguma coisa lá deveria verificar se o número está de acordo com a norma. (móvel começa por 91, 92, 93, 96 e os fixos por 2 qualquer coisa, tendo em conta que há indicativos com 3 digitos) em termos de segurança seria melhor fazer essa verificação em PHP. o que tenho até agora é isto mas sinceramente não é grande coisa. <?php if (substr(trim($telephone), 0, 2) == '91') { // number starts with 91 } else { if (substr(trim($telephone), 0, 2) == '92') { // number starts with 92 } else { if (substr(trim($telephone), 0, 2) == '93') { // number starts with 93 } else { if (substr(trim($telephone), 0, 2) == '96') { // number starts with 96 } else { echo "Invalid Phone number"; } } } } ?> o que uso de jquery é só mesmo para ficar visualmente bonito Edited July 27, 2012 by sEnte "If It Ain't Broke, Break it and build something Cooler!" Unknown Link to comment Share on other sites More sharing options...
HappyHippyHippo Posted July 27, 2012 Report Share Posted July 27, 2012 (edited) se usas o jquery validate, podes definir novos tipos de dados: um exemplo para número de telefone seria <!DOCTYPE html> <html> <head> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> <script type="text/javascript" src="jquery.validate.min.js"></script> <script type="text/javascript"> jQuery.validator.addMethod( "type_telefone", function(value, element) { var check = true; /* validar numeros moveis (91x, 92x, 93x, 96x) e fixos (2x) */ var re = /^(9[1236]\d{7}|2\d{8})$/; if (value == "") /* campo obrigatorio */ check = false; else if(re.test(value) == false) check = false; return check; }, "Numero invalido"); $(document).ready(function(){ $('#test').validate({rules: { telefone: 'type_telefone'}}); }); </script> </head> <body> <form id="test"> <input id="telefone" name="telefone" /> <input type="submit" /> </form> </body> </html> para tratar do do lado do servidor podes usar a mesma expressão regular $re = '/^(9[1236]\d{7}|2\d{8})$/'; if(preg_match($re, trim($_REQUEST['telefone'])) == 0) { // invalid } Edited July 27, 2012 by HappyHippyHippo IRC : sim, é algo que ainda existe >> #p@p Portugol Plus Link to comment Share on other sites More sharing options...
sEnte Posted July 27, 2012 Author Report Share Posted July 27, 2012 De qualquer forma obrigado. Vou fazer umas reformulações no meu PHP de enviar mail. Depois digo alguma coisa. Posso no entanto enviar mail que é como quem diz mensagem privada? "If It Ain't Broke, Break it and build something Cooler!" Unknown Link to comment Share on other sites More sharing options...
sEnte Posted July 28, 2012 Author Report Share Posted July 28, 2012 (edited) Aqui está o meu send_mail 🙂 <?php if (isset($_POST['contact_name']) && isset($_POST['contact_email']) && isset($_POST['contact_phone']) && isset($_POST['contact_subject']) &&isset($_POST['contact_text'])) { $contact_name = $_POST['contact_name']; $contact_email = $_POST['contact_email']; $contact_phone = $_POST['contact_phone']; $contact_subject = $_POST['contact_subject']; $contact_message = $_POST['contact_text']; if(!empty($contact_name) && !empty($contact_email) && !empty($contact_phone) && !empty($contact_subject) && !empty($contact_text)){ if (strlen($contact_name)>25 || strlen($contact_email)>50 || strlen($contact_phone)>9 || strlen($contact_subject)>25 || strlen($contact_message)>2500){ echo 'Max length reached'; } else { $to = 'mais1@qualquercoisa.net'; $for = $contact_email; $headers = 'From: '.$contact_email; $subject = $contact_subject; $body = $contact_name . "\n" . $contact_phone . "\n" . $contact_message; if (@mail($to, $subject, $body, $headers)){ echo 'Thanks for contacting us!'; } else { echo 'Error!'; } } } else { echo 'Your message was not sent!'; } // Cópia do mail enviado. mail($for, $subject, $body, $headers); } ?> <!-- Validate email --> <?php if (isset($_POST['contact_email']) == true && empty ($_POST['contact_email']) == false){ $email = $_POST['contact_email']; if (filter_var($email, FILTER_VALIDATE_EMAIL) == true){ echo 'Valid email'; } else { echo 'Invalid email'; } } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title></title> </head> <body> <form action="index.php" method="post"> <table width="367" border="0"> <tr> <td width="94"></td> <td width="263"><input type="text" name="contact_name" maxlength="25" placeholder="Name"></td> </tr> <tr> <td></td> <td> <input type="text" name="contact_email" maxlength="50" placeholder="Email"></td> </tr> <tr> <td></td> <td><input type="text" name="contact_phone" maxlength="9" placeholder="Phone"></td> </tr> <tr> <td></td> <td><input type="text" name="contact_subject" maxlength="25" placeholder="Subject"></td> </tr> <tr> <td></td> <td><textarea name="contact_text" rows="6" cols="30" maxlength="2500" placeholder="Messsage"></textarea></td> </tr> <!-- <tr> <td>Captcha</td> <td></td> </tr>--> <tr> <td></td> <td><input type="submit" value="Send"></td> </tr> </table> </form> </body> </html> nada de muito complicado e faz umas verificações e tal. Agora a dificuldade é adicionar isso aqui... :S já agora o Validation que uso é este http:// jorenrapini.com/posts/validation/ (Quebrei o link porque não sei se é permitido meter links para o exterior ou não) Edited July 28, 2012 by sEnte "If It Ain't Broke, Break it and build something Cooler!" Unknown Link to comment Share on other sites More sharing options...
HappyHippyHippo Posted July 28, 2012 Report Share Posted July 28, 2012 1º - não vejo nenhuma referência ao validador de dados em javascript 2º - porque raio validar o email depois de enviar o email 3º - ao responder ao segundo ponto respondes ao pormenor de onde deverás colocar o código de validação do número de telefone IRC : sim, é algo que ainda existe >> #p@p Portugol Plus Link to comment Share on other sites More sharing options...
sEnte Posted July 28, 2012 Author Report Share Posted July 28, 2012 (edited) 1º pois não, não adicionei isso neste código mas posso adicionar depois. queria um que fizesse outline (tipo focus) a vermelho com uma mensagem ao lado. Não sei se me estou a fazer entender. 2º - melhor sitio para o colocar é assim certo? $to = 'mais1@qualquercoisa.net'; $for = $contact_email; $headers = 'From: '.$contact_email; $subject = $contact_subject; $body = $contact_name . "\n" . $contact_phone . "\n" . $contact_message; if (isset($_POST['contact_email']) == true && empty ($_POST['contact_email']) == false){ $email = $_POST['contact_email']; if (filter_var($email, FILTER_VALIDATE_EMAIL) == true){ echo 'Valid email'; } else { echo 'Invalid email'; } } $re = '/^(9[1236]\d{7}|2\d{8})$/'; if(preg_match($re, trim($_REQUEST['$contact_phone'])) == 0) { // invalid } if (@mail($to, $subject, $body, $headers)){ echo 'Thanks for contacting us!'; } else { echo 'Error!'; } } Edited July 28, 2012 by sEnte "If It Ain't Broke, Break it and build something Cooler!" Unknown Link to comment Share on other sites More sharing options...
HappyHippyHippo Posted July 28, 2012 Report Share Posted July 28, 2012 sim, mas não estás a bloquear o envio do email caso a informação esteja errada IRC : sim, é algo que ainda existe >> #p@p Portugol Plus Link to comment Share on other sites More sharing options...
sEnte Posted July 28, 2012 Author Report Share Posted July 28, 2012 Não perccebi. desculpa "If It Ain't Broke, Break it and build something Cooler!" Unknown Link to comment Share on other sites More sharing options...
yoda Posted July 28, 2012 Report Share Posted July 28, 2012 O que ele te quis dizer é que o código que tens vai imprimir a mensagem de erro caso exista um erro no formulário, mas como a existência de erros não está a ser verificada, o sistema vai tentar enviar o email mesmo com erros. Experimenta assim : $to = 'mais1@qualquercoisa.net'; $for = $contact_email; $headers = 'From: '.$contact_email; $subject = $contact_subject; $body = $contact_name . "\n" . $contact_phone . "\n" . $contact_message; $errors = array(); if ($_POST) { $email = isset($_POST['contact_email']) ? trim($_POST['contact_email']) : false; $phone = isset($_POST['contact_phone']) ? trim($_POST['contact_phone']) : false; if ($email) { if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { $errors[] = 'Invalid email'; } } else { $errors[] = 'Email missing'; } if ($phone) { $regex_phones = '/^(9[1236]\d{7}|2\d{8})$/'; if(preg_match($regex_phones, $phone) == 0) { $errors[] = 'Invalid phone number'; } } } if (empty($errors)) { if (@mail($to, $subject, $body, $headers)) { echo 'Thanks for contacting us!'; } else { echo 'Error!'; } } else { foreach ($errors as $error) { echo $error; } } before you post, what have you tried? - http://filipematias.info sense, purpose, direction Link to comment Share on other sites More sharing options...
sEnte Posted July 28, 2012 Author Report Share Posted July 28, 2012 (edited) Obrigado peloa ajuda yoda. Então o cod todo fica assim certo? .... está a dar erro na linha 73 (linha a seguir ao fecho da tag php EDIT1: Fui a este site phpcodechecker.com e obtive estes resultados... Error: There are 2 more opening curly braces '{' than expected PHP Syntax Check: Parse error: syntax error, unexpected $end in your code on line 72 PHP Syntax Check: Errors parsing your code Já tentei procurar erros mas onde me pareceu que era, afinal não é!!! EDIT2: Código removido... Afinal já descobri os erros. Tive de indentar o código e usar o Notepad++ que ajudou. Ainda não experimentei mas se ficar tudo a funcionar pode-se fechar isto Edited July 28, 2012 by sEnte "If It Ain't Broke, Break it and build something Cooler!" Unknown Link to comment Share on other sites More sharing options...
taviroquai Posted July 28, 2012 Report Share Posted July 28, 2012 <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js%22></script> <script type="text/javascript" src="jquery.validate.min.js"></script> <script type="text/javascript"> jQuery.validator.addMethod( "type_telefone", function(value, element) { var check = true; /* validar numeros moveis (91x, 92x, 93x, 96x) e fixos (2x) */ var re = /^(9[1236]\d{7}|2\d{8})$/; if (value == "") /* campo obrigatorio */ check = false; else if(re.test(value) == false) check = false; return check; }, "Numero invalido"); $(document).ready(function(){ $('#test').validate({rules: { telefone: 'type_telefone'}}); }); </script> Interessante... desconhecia isto... bem bom 🙂 Link to comment Share on other sites More sharing options...
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now