Validate email inside textarea - javascript

I made a form with only a textarea, so i want the form be validate only if the message has a valid email inside the textarea,
But if i use FILTER_VALIDATE_EMAIL, it's allows only email, without space or message.
How can i fix it?
My code:
<form action="contact.php" method="post">
<p>
<textarea rows="1" style="height:1em;" id="text" autofocus>Hello my name is M2PV,
</textarea>
</p>
<p>
<input value="send" type="submit" id="send">
</p>
</form>
$('form').submit(function(){
message = $(this).find('#text').val();
$.post('contact.php',{
message:message
}, function(data){
if(data.error=='ok'){
alert('formulaire ok');
}else{
alert('email invalid');
}
},"json");
return false;
});
});
<?php
$e= array();
$e['error'] = "Entrez votre email";
if(!filter_var($_POST['message'], FILTER_VALIDATE_EMAIL)){
$e['email_invalid'] = "email_invalid";
}else{
$e['error'] = 'ok';
$message = $_POST['message'];
$to = 'xxxx#xx.com';
$sujet = ' Contact site ';
$msg = $message;
//mail($to, $sujet, $msg);
}
echo json_encode($e)
?>

My suggestion is to parse all e-mail addresses and validate them
HERE you can find inspiration for parsing multiple e-mail addresses and put them in an array. After that you could iterate over the array and validate them

Related

Run PHP after JS validation

I am doing email validation for admin registration using JavaScript and save the data to database using PHP. Supposedly, the registration is done only if the email is valid. But when the email evaluates to invalid, the PHP code still run. How do I do it so that when the email is invalid, the PHP won't run.
Below is the PHP code to save data to database:
<?php
include('connection.php');
if(isset($_POST['saveBtn']))
{
$name = $_POST['name'];
$ic = $_POST['ic'];
$email = $_POST['email'];
$pass = $_POST['pass'];
$dob = $_POST['dob'];
$contact = $_POST['contact'];
$gender = $_POST['gender'];
$des = $_POST['des'];
$address = $_POST['address'];
// Check if data exist
$check = "SELECT * FROM admin WHERE admEmail = '".$email."' AND admPassword = '".$pass."'";
if(mysqli_num_rows(mysqli_query($connect,$check)) > 0)
{
?>
<script>
alert('This email and password already registered!');
</script>
<?php
}
else
{
$insert = "INSERT INTO admin (admName, admIC, admEmail, admPassword, admDOB, admContact, admGender, admDesignation, admAddress, admDateJoin) VALUES ('".$name."', '".$ic."', '".$email."', '".$pass."', '".$dob."', '".$contact."', '".$gender."', '".$des."', '".$address."', NOW())";
if(mysqli_query($connect, $insert))
{
?>
<script>
alert('Insertion Successful!');
window.close();
window.opener.location.reload();
</script>
<?php
}
else
{
?>
<script>
alert('Insertion Failed. Try Again!');
</script>
<?php
}
}
}
?>
Below is the JS:
function validateEmail() {
var email = document.addAdminForm.email.value;
var validRegex = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+#[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;
if (email.match(validRegex))
{
alert("Valid email address!");
return true;
}
else
{
document.getElementById("email_error").innerHTML = "Invalid email";
document.addAdminForm.email.focus();
return false;
}
}
Below is the partial HTML form:
<form class="w-100" name="addAdminForm" method="POST" onsubmit="validateEmail(this)" action="add_admin.php">
<div class="row">
<div class="col form-group">
<!-- <label for="email">Email</label> -->
<input type="text" class="form-control" name="email" placeholder="Email" required>
<span class="error email_error" id="email_error"></span>
</div>
<div class="float-right">
<input type="submit" class="btn button_primary" value="Save" name="saveBtn">
</div>
</form>
I expect PHP run when validation is true
add this:
onsubmit="return validateEmail(this)"
change your JS code to:
var validRegex = /^([a-zA-Z0-9_-])+#([a-zA-Z0-9_-])+((\.[a-zA-Z0-9_-]{2,3}){1,2})$/;

Ajax Form Not Doing Anything

I have a form using Ajax that is suppose to show an error to the user when something is incorrect when the login. When I click the submit button nothing happens. I hate asking Stack overflow but you got to do what you got to do. And yes, I have Apache configured to not need file extensions.
This is the tutorial I am following: https://www.youtube.com/watch?v=L7Sn-f36TGM
Login Script:
require("dbh.php");
if(isset($_POST['submit'])) {
$email = $_POST['email'];
$pwd = $_POST['pwd'];
$errorEmpty = false;
$errorEmail = false;
$errorWrong = false;
if(empty($email) || empty($pwd)) {
echo "<p class='loginText'>Please Enter an Email Address and Password!</p>";
$errorEmpty = true;
} else if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "<p class='loginText'>Please Enter a Valid Email Address!</p>";
$errorEmail = true;
} else {
echo "Success!";
}
} else {
echo "<p class='loginText'>An Error Occurred!</p>"
}
header("/login?test");
loginForm.js
$(document).ready(function() {
$("#loginFormInput").submit(function(event) {
event.preventDefault();
var email = $("#emailLogin").val();
var pwd = $("#pwdLogin").val();
$(".errorText").load("../php-scripts/login", {
email: email,
pwd: pwd
});
});
});
HTML Form:
<p class="errorText"></p>
<form action="../php-scripts/login.php" method="post" id="loginFormInput">
<input type="text" name="email" class="textInput" id="emailLogin" placeholder="Email" maxlength="512"> <br>
<input type="password" name="pwd" class="textInput" id="pwdLogin" placeholder="Password" maxlength="1024"> <br>
<p class="rememberText">Remember Me:</p>
<input type="checkbox" name="remember" class="rememberBox"> <br>
<input type="submit" value="Login" name="submit" class="submitInput" title="Login">
</form>
Your PHP code is doing if (isset($_POST['submit'])), but when you do the AJAX submission you don't provide a submit parameter. You need to add that to the parameters:
$(".errorText").load("../php-scripts/login", {
email: email,
pwd: pwd,
submit: 'Login'
});
Or you could remove that check from the PHP, if that script is only used to process the AJAX requests.
I think you're missing an element with class name errorText
Try adding a <div class="errorText"></div> somewhere

Ajax/php contact form sending blank emails from time to time

Well I have this contact form that sends blank emails. But I did some testing and it doesn't happens to me. The only way this could happen, I think, would be by accesing the .php file directly. If not I don't know what could be the problem. The form doesn't let you send a blank email. If this keeps happening I'm going to add a validation in the php file too, but until I find out what is the problem I don't want to ignore this messages.
This is the HTML
<form name="contactForm" id="contactForm" method="post" action="/contactEngine.php" onsubmit="return validateForm()">
<input title="Input name" type="text" name="Name" id="Name" placeholder="Nombre:" required="">
<input title="Input email" placeholder="Email:" type="email" name="Email" id="Email" required="">
<input type="text" placeholder="Subject:" name="Subjet" id="Subjet">
<textarea title="Input message" placeholder="Mensaje:" name="Message" rows="20" cols="20" id="Message" required=""></textarea>
<input title="Input result" placeholder="25 + 25 = ?" type="text" name="Captcha" id="Captcha" required="">
<p id="wrongCaptcha"> Try again </p>
<input type="submit" name="submit" value="send" class="submit-button">
</form>
This is the JS
function validateForm(e) {
e.preventDefault();
var x = document.forms["contactForm"]["Captcha"].value;
if (x != 50) {//if captcha is wrong
$("#Captcha").addClass("wrongCaptchaEntered");
$("#Captcha").css("animation-name" , "none");
setTimeout (function(){
$("#Captcha").css("animation-name" , "changeBorder");
},100);
if ($("#wrongCaptcha").css("display") == "none"){
$("#wrongCaptcha").slideDown();
}
}
else { //if captcha is correct
var formAction = $("#contactForm").attr("action");
if (formAction == "/contactEngine.php"){
var formData = $("#contactForm").serialize();
$.post( formAction, formData, function(data){
console.log (data);
$(".formulario").changeTo({content: "<h2 class='section-title BackgroundGradientBlack'>"+ data +"</h2>"});
});
}
}
return false;
}
And the PHP
<?php
$EmailFrom = "EmailFrom#test.com";
$EmailTo = "EmailTo#test.com";
$Name = Trim(stripslashes($_POST['Name']));
$Email = Trim(stripslashes($_POST['Email']));
$Subject = Trim(stripslashes($_POST['Subjet']));
$Message = Trim(stripslashes($_POST['Message']));
$email_content = "Frontpage";
$email_content .= "\nNombre: $Name";
$email_content .= "\nEmail: $Email";
$email_content .= "\nMotivo: $Subject";
$email_content .= "\nMensaje: $Message";
$email_headers = "From: <$EmailFrom>";
if (mail($EmailTo, $Subject, $email_content, $email_headers)) {
http_response_code(200);
echo "Mensaje enviado";
} else {
http_response_code(500);
echo "Error";
}
?>
Thanks!
Probably some bot that's testing the PHP endpoint it can see in your JS and is sending data to it, trying to cause havoc. I bet if you logged the $_POST variable every time an email was sent, you'd seen a lot of spammy nonsense in some $_POST variables. Emails are blank just because the bots aren't smart enough to know which keys to use in its POSTs.

My page does not stay the same page when I click the option submit

I'm a little new here. I tried to make my website on my own and although it is almost finished, I can not solve the problem of sending information in my contact form.
The page is this: ramproducciones.pe (it's in Spanish)
If they go towards the end they find the contact form, even if they fill the data correctly, the email is sent but the next thing is that a blank page is given. What I want is that you get a message that says Thank you! Your message has been sent but I do not know how to do it. I have tried to copy many codes and I currently have this:
<!-- contacto-->
<section class="contact" id="contact">
<h1>Contacto</h1>
<hr/>
<div class="content">
<div class="form">
<form method="post" action="mail.php" name="contact">
<div class="column">NOMBRE<br/><br/>
<input name="name" id="name" value="" />
</div>
<div class="column-2">E-MAIL<br/><br/>
<input name="email" id="email" value="" />
</div>
<div class="column-3">MENSAJE<br/><br/>
<textarea id="message" name="message" ></textarea>
</div>
<div class="button">
<span><input class="submit" id="submit" name="submit" type="submit" value="ENVIAR"></span>
</div>
<div id="dialog-message" title="Thank You">
<p>¡Gracias! Tu mensaje ha sido enviado, te responderemos lo antes posible.</p>
</div>
</form>
</div>
<div class="contact-text">
No dudes en solicitarnos información.<br/><br/>
<strong>RAM Producciones</strong><br/><br/>
e-mail: <strong>info#ramproducciones.com</strong>
<br/><br/>
<img src=img/social/Facebook.png />
<img src=img/social/Vimeo.png />
<img src=img/social/Behance.png />
<img src=img/social/Instagram.png />
<img src=img/social/Youtube.png />
</div>
</div>
</section>
AND THE PHP is
<?php
// define variables and set to empty values
$name_error = $email_error = "";
$name = $email = $message = $success = "";
//form is submitted with POST method
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$name_error = "Name is required";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$name_error = "Solo ingresa letras y espacios.";
}
}
if (empty($_POST["email"])) {
$email_error = "Tu E-mail es necesario";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$email_error = "Formato de E-mail inválido";
}
}
if (empty($_POST["message"])) {
$message = "";
} else {
$message = test_input($_POST["message"]);
}
if ($name_error == '' and $email_error == '' and $phone_error == '' and $url_error == '' ){
$message_body = '';
unset($_POST['submit']);
foreach ($_POST as $key => $value){
$message_body .= "$key: $value\n";
}
$to = 'info#ramproducciones.pe';
$subject = 'Mail vía RAMPRODUCCIONES.PE';
if (mail($to, $subject, $message)){
$success = "¡Gracias! Tu mensaje ha sido enviado, te responderemos lo antes posible.";
$name = $email = $message = '';
}
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
However I still can not solve the problem.
It's your action. You're sending your page to another page called mail.php. Set the action to reload your current page when the form is submitted.
Try using
<form id='form' method='post' action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>'>
as an attribute in your form
In the top of your page where you run your code for successful form submission, hide the form then display your message.
echo "<style>#form{display:none}</style>";
echo "<p>Thank you for submitting</p>";
There are a lot of possibilities in your case. Clearshot66 has introduced one.
Another possibility would be to keep your mail.php page and after the sending of the e-mail, you could create a logic to send the user back to your main page and show him a message. This could be done as I show you below:
mail.php
header("Location: your_main_page.php?showMessage=1");
exit;
your_main_page.php
<?php
if ($_GET["showMessage"] == 1) {
echo "Thanks for your contact.";
}
?>
The above code should be put in the beggining of your main_page.php
This is another IDEA.
The best good practice is to send the form using some ajax request and handle the return of this request, but this is a little bit more sofisticated than the options that we pointed to you.
As #clearshot66 said, you are redirecting to mail.php. I understand, that the php page you mean is this file.
What Fredi -ii- saw, you forgot to echo $success.
Blank page happens, because there is no output.
Hope I helped.

AJAX send text in only one line

I have a problem with an ajax request.
I have a form that has two text input and a textarea and an ajax function that sends to another page called mail.php the text of the three input, then mail.php sends an e-mail with those data and return 1 if the e-mail was sent correctly and 0 if not. It works but in the arrived e-mail the text is only in one line also if in the textarea i have got 3 or 4 line.
This is the form:
<div id="form">
<input type="email" class="style" id="mail" maxlength="80" placeholder="Inserisci la tua e-mail" required />
<br>
<input type="text" class="style" id="subject" maxlength="50" placeholder="Oggetto" required />
<br>
<textarea id="message" class="style" placeholder="Scrivi il messaggio..." rows="8" maxlength="2000" required></textarea>
<br>
<button type="submit" id="submit_button"><div><p class="send_button_content">Invia</p><img id="send_button_icon" class="send_button_content" src="send_icon.png"></div></button>
</div>
And this is the ajax function:
function sendEmail(){
var mail;
var subject;
var message;
mail = $("#mail").val();
subject = $("#subject").val();
message = $("#message").val();
if (mail !="" && subject !="" && message !="") {
if (emailCheck(mail)){
$.post("mail.php",{mail: mail,subject: subject,message: message},function(data){alert(data);});
}else{
alert("The e-mail is not correct")
}
} else {
alert("Fill all");
}
}
$("#submit_button").click(function(){sendEmail(); });
And mail.php is like this:
$mail = $_POST['mail'];
$subject = "Nuovo messaggio: ".$_POST['subject'];
$message = "<html>
<head>
</head>
<body>
<p>New message from: ".$mail."<br>
Message: ".$_POST['message']."<br>
<a href='mailto:".$mail."?subject=".$_POST['subject']."' style='color:blue' target='_blank'>Reply here</a>
</p>
</body>
</html>";
if($mail != "" && $subject != "" && $message != ""){
$to = "***********#gmail.com";
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$result = mail($to,$subject,$message,$headers) or die('0');
if(result){
die('1');
}else{
die('0');
}
}else{
die('0');
}
Is there a method that take the text as I have written and send it?
use nl2br()
$message=nl2br($_POST['message']);

Categories

Resources