Telephone field validation using JQuery and PHP - javascript

I have a contact form with simple jQuery validation, and sending the form content using Php. I'm trying to include a phone field validation. JavaScript works fine when validating the phone field and auto format/correcting/completing the phone field. However the Php script is not working. It works fine if I remove the the phoneNumber field.
(function($) {
"use strict";
/* Alert Boxes
* ------------------------------------------------------ */
var clAlertBoxes = function() {
$('.alert-box').on('click', '.alert-box__close', function() {
$(this).parent().fadeOut(500);
});
};
/* Contact Form
* ------------------------------------------------------ */
var clContactForm = function() {
/* local validation */
$('#contactForm').validate({
/* submit via ajax */
submitHandler: function(form) {
var sLoader = $('.submit-loader');
$.ajax({
type: "POST",
url: "inc/sendEmail.php",
data: $(form).serialize(),
beforeSend: function() {
sLoader.slideDown("slow");
},
success: function(msg) {
// Message was sent
if (msg == 'OK') {
sLoader.slideUp("slow");
$('.message-warning').fadeOut();
$('#contactForm').fadeOut();
$('.message-success').fadeIn();
}
// There was an error
else {
sLoader.slideUp("slow");
$('.message-warning').html(msg);
$('.message-warning').slideDown("slow");
}
},
error: function() {
sLoader.slideUp("slow");
$('.message-warning').html("Something went wrong! Please try again.");
$('.message-warning').slideDown("slow");
}
});
}
});
};
})(jQuery);
fieldset {
margin: 0;
padding: 0;
}
.message-warning,
.message-success {
display: none;
background: #111111;
font-size: 1.5rem;
line-height: 2;
padding: 3rem;
margin-bottom: 3.6rem;
width: 100%;
}
.message-warning {
color: #ff6163;
}
.message-success {
color: #39b54a;
}
.message-warning i, .message-success i {
margin-right: 10px;
font-size: 1.2rem;
}
/* form loader
* ----------------------------------------------- */
.submit-loader {
display: none;
position: relative;
left: 0;
top: 1.8rem;
width: 100%;
text-align: center;
margin-bottom: 3rem;
}
.submit-loader .text-loader {
display: none;
font-family: "montserrat-regular", sans-serif;
font-size: 1.3rem;
font-weight: bold;
line-height: 1.846;
color: #666666;
letter-spacing: .2rem;
text-transform: uppercase;
}
.oldie .submit-loader .s-loader {
display: none;
}
.oldie .submit-loader .text-loader {
display: block;
}
/* ---------------------------------------------------------------
* ## loader animation
* --------------------------------------------------------------- */
.s-loader {
margin: 1.2rem auto 3rem;
width: 70px;
text-align: center;
-webkit-transform: translateX(0.45rem);
-ms-transform: translateX(0.45rem);
transform: translateX(0.45rem);
}
.s-loader > div {
width: 9px;
height: 9px;
background-color: #FFFFFF;
border-radius: 100%;
display: inline-block;
margin-right: .9rem;
-webkit-animation: bouncedelay 1.4s infinite ease-in-out both;
animation: bouncedelay 1.4s infinite ease-in-out both;
}
.s-loader .bounce1 {
-webkit-animation-delay: -0.32s;
animation-delay: -0.32s;
}
.s-loader .bounce2 {
-webkit-animation-delay: -0.16s;
animation-delay: -0.16s;
}
<?php
<?php
// Replace this with your own email address
$siteOwnersEmail = 'testemail#outlook.com';
if($_POST) {
$name = trim(stripslashes($_POST['contactName']));
$email = trim(stripslashes($_POST['contactEmail']));
$phone = stripslashes($_POST['phoneNumber']);
$subject = trim(stripslashes($_POST['contactSubject']));
$contact_message = trim(stripslashes($_POST['contactMessage']));
// Check Name
if (strlen($name) < 2) {
$error['name'] = "Please enter your name.";
}
// Check Email
if (!preg_match('/^[a-z0-9&\'\.\-_\+]+#[a-z0-9\-]+\.([a-z0-9\-]+\.)*+[a-z]{2}/is', $email)) {
$error['email'] = "Please enter a valid email address.";
}
// Check Phone
if(!preg_match("/^[0-9]{3}-[0-9]{4}-[0-9]{4}$/", $phone)) {
$error['phone'] = "Please enter a valid phone number.";
}
// Check Message
if (strlen($contact_message) < 15) {
$error['message'] = "Please enter your message. It should have at least 15 characters.";
}
// Subject
if ($subject == '') { $subject = "Contact Form Submission"; }
// Set Message
$message .= "Email from: " . $name . "<br />";
$message .= "Email address: " . $email . "<br />";
$message .= "Contact Phone: " . $phone . "<br />";
$message .= "Message: <br />";
$message .= $contact_message;
$message .= "<br /> ----- <br /> This email was sent from your site's contact form. <br />";
// Set From: header
$from = $name . " <" . $email . ">";
// Email Headers
$headers = "From: " . $from . "\r\n";
$headers .= "Reply-To: ". $email . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
if (!$error) {
ini_set("sendmail_from", $siteOwnersEmail); // for windows server
$mail = mail($siteOwnersEmail, $subject, $message, $headers);
if ($mail) { echo "OK"; }
else { echo "Something went wrong... Please try again."; }
} # end if - no validation error
else {
$response = (isset($error['name'])) ? $error['name'] . "<br /> \n" : null;
$response .= (isset($error['email'])) ? $error['email'] . "<br /> \n" : null;
$response .= (isset($error['phone'])) ? $error['phone'] . "<br /> \n" : null;
$response .= (isset($error['message'])) ? $error['message'] . "<br />" : null;
echo $response;
} # end if - there was a validation error
}
?>
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://rawgit.com/RobinHerbots/jquery.inputmask/3.x/dist/jquery.inputmask.bundle.js"></script>
<div class="default-form contact-form">
<form method="post" action="" id="contactForm" novalidate="novalidate">
<fieldset>
<div class="form-group">
<input type="text" name="contactName" id="contactName" value="" placeholder="Complete Name" minlength="4" required="" aria-required="true">
</div>
<div class="form-group">
<input type="email" name="contactEmail" id="contactEmail" value="" placeholder="Your Email" required="" aria-required="true">
</div>
<div class="form-group">
<input placeholder="Phone" type="text" id="phoneNumber" name="phoneNumber" required="" aria-required="true">
<script type="text/javascript">
$('#phoneNumber').inputmask("(999) 999-9999");
</script>
</div>
<div class="form-group">
<input type="text" name="contactSubject" id="contactSubject" value="" placeholder="Subject" required="" aria-required="true">
</div>
<div class="form-group">
<input type="text" name="contactMessage" id="contactMessage" value="" placeholder="Your Message" required="" aria-required="true">
</div>
<div class="form-group">
<button class="full-width btn btn--primary">Submit</button>
<div class="submit-loader">
<div class="text-loader">Sending...</div>
<div class="s-loader">
<div class="bounce1"></div>
<div class="bounce2"></div>
<div class="bounce3"></div>
</div>
</div>
</div>
</fieldset>
</form>
<!-- contact-warning -->
<div class="message-warning">
Something went wrong. Please try again.
</div>
<!-- contact-success -->
<div class="message-success">
Your message was sent, thank you!<br>
</div>
</div>
<!--End Default Form-->

You can preg_match() to validate 10-digit mobile numbers:
preg_match('/^[0-9]{10}+$/', $mobile)

Problem solved.. I changed the inputmask to this format ("999-999-9999"), then also made a change to Php to match the js inputmask, it goes something like:
if(!preg_match('/^[0-9]{3}-[0-9]{3}-[0-9]{4}$/', $phone)) {
$error['phone'] = "Please enter a valid phone number.";
}

Try this method :
function validating($phone){
$valid_number = filter_var($phone, FILTER_SANITIZE_NUMBER_INT);
$valid_number = str_replace("-", "", $valid_number);
if (strlen($valid_number) < 10 || strlen($valid_number) > 14) {
echo "Invalid Number <br>";
} else {
echo "Valid Number <br>";
}
}
$phone = "(999) 999-9999";
validating($phone);

Related

Show something while data is being searched on databse

I want to show a gif while the user's username and password are being validated, but my ajax code isn't storing the submited data, then nothing happens.
login.php (where the inputs are)
<div>
<input type="text" class="css-input" placeholder="Insira seu código" required="" name="codigo" style="background: url(images/icons/user_o.png) no-repeat scroll 5px 5px; background-size: 25px; background-color: #FFFFFF;color: #FF5400;"/>
</div>
<div>
<input type="password" class="css-input" placeholder="Senha" required="" name="senha" style="background: url(images/icons/pwd.png) no-repeat scroll 5px 5px; background-size: 25px;"/>
</div>
login2 (validation form)
<?php
$codigo = mysqli_real_escape_string($conexao, $_POST['codigo']);
$senha = mysqli_real_escape_string($conexao, $_POST['senha']);
$sql_codigo = "SELECT * FROM esc_usuarios WHERE usu_codigo = '$codigo'";
$sql_nome = "SELECT usu_nome FROM esc_usuarios WHERE usu_codigo = '$codigo'";
$sql_nome_resul = mysqli_query($conexao, $sql_nome);
$coluna_bd = mysqli_fetch_assoc($sql_nome_resul);
$result = mysqli_query($conexao, $sql_codigo);
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_array($result))
{
if(password_verify($senha, $row['usu_senha']))
{
$_SESSION['codigo']=$codigo;
echo '<p><span style="font-family: calibri, sans-serif;"><span style="color: #a1eb8f; font-size: 17pt;">Olá ' . $coluna_bd['usu_nome'] . '! Aguarde um instante...</span></span></p>';
$response['type'] = 'success';
}
else
{
echo '<p><span style="font-family: calibri, sans-serif; color: #ff8f57;"><span style="font-size: 17pt;">Usuário e/ou senha incorretos!</span></span></p>';
$response['type'] = 'failure';
}
echo json_encode($response);
}
}
?>
javascript.js (ajax not working)
$("#login").click(function(){
$.get("login2.php", {codigo: codigo, senha: senha}, function(data){
if (data.type == "success"){
window.location = "index.php";
}
else{
window.location = "login.php";
}
}, "JSON");
});
So, I didn't actually made the gif part yet because I'm trying to at least go through this part, but without success so far.

php mail() sending mail before form is filled

I have a self posting document that has form fields to fill out with php processing on the same document. My problem is that upon opening the page (website), the message "Message Sent!" shows up immediately before the form can be filled out with information. The php mail() function is linked to my email account so I get the form data email. But no data is sent because the email was sent before the form could be filled out. I want to be able to fill out the form before the email is sent off so that way the form sends actual information. Ive researced this topic and came up with nothing. Any help would be awesome! Here's my code...
<?php
foreach($_POST as $key => $value) //This will loop through each name-value in the $_POST array
{
$tableBody .= "<tr>"; //formats beginning of the row
$tableBody .= "<td>$key</td>"; //dsiplay the name of the name-value pair from the form
$tableBody .= "<td>$value</td>"; //dispaly the value of the name-value pair from the form
$tableBody .= "</tr>"; //End this row
}
echo "<table border='1'>";
echo "<tr><th>Field Name</th><th>Value of field</th></tr>";
foreach($_POST as $key => $value)
{
echo '<tr class=colorRow>';
echo '<td>',$key,'</td>';
echo '<td>',$value,'</td>';
echo "</tr>";
}
echo "</table>";
echo "<p> </p>";
?>
<!DOCTYPE html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<style>
body {
background-image: url("rbGrid.png");
background-size: 150%;
background-repeat: no-repeat;
text-align: center;
}
div {
background-color: black;
opacity: 0.9;
color: white;
text-align: center;
}
h1 {
color: white;
}
h2 {
color: white;
}
#borderStyle {
border: double thick red;
border-radius: 45px;
width: 50%;
margin: 0 auto;
}
#hiddenStuff {
display: none;
}
textarea {
display: none;
margin: 0 auto;
}
#mailingInformation {
display: none;
margin: 0 auto;
}
table {
margin: 0 auto;
border: solid thick red;
border-radius: 20px;
}
th {
border: solid thick red;
border-radius: 45px;
}
tr {
color: white;
border: solid thin red;
border-radius: 45px;
}
td {
color: white;
border: solid thin red;
border-radius: 45px;
}
</style>
<script>
function showProductProblemComments()
{
document.getElementById("textarea").style.display = "block";
}
function showMailingListForm()
{
document.getElementById("mailingInformation").style.display = "block";
}
</script>
</head>
<body>
<?php
$toEmail = "robinjennings#nephilim42.com"; //CHANGE within the quotes. Place email address where you wish to send the form data.
//Use your DMACC email address for testing.
$subject = "WDV341 Email Example"; //CHANGE within the quotes. Place your own message. For the assignment use "WDV101 Email Example"
$fromEmail = "robinjennings#nephilim42.com"; //CHANGE within the quotes. Use your DMACC email address for testing OR
//use your domain email address if you have Heartland-Webhosting as your provider.
// DO NOT CHANGE THE FOLLOWING LINES //
$emailBody = "Form Data\n\n "; //stores the content of the email
foreach($_POST as $key => $value) //Reads through all the name-value pairs. $key: field name $value: value from the form
{
$emailBody.= $key."=".$value."\n"; //Adds the name value pairs to the body of the email, each one on their own line
}
$headers = "From: $fromEmail" . "\r\n"; //Creates the From header with the appropriate address
if (mail($toEmail,$subject,$emailBody,$headers)) //puts pieces together and sends the email to your hosting account's smtp (email) server
{
echo("<p>Message successfully sent!</p>");
}
else
{
echo("<p>Message delivery failed...</p>");
}
/*$inName = $_POST["Name"];
$inEmail = $_POST["Email Address"];
$inAddress = $_POST["address"];
$inReason = $_POST["Reason"];
$inComments = $_POST["comments"];
$inMailBox = $_POST["Mailing List"];
$inUseAddress = $_POST["checkForAddress"];
$inFirstName = $_POST["mailingName"];
$inLastName = $_POST["mailingLastName"];
//$inMailingAdd $_POST["mailingAddress"];
$inPhoneNumber = $_POST["phoneNumber"];
$inMoreInfo = $_POST["More Info"];*/
?>
<h1>WDV341 Intro PHP</h1>
<h2>Programming Project - Contact Form</h2>
<div>
<form name="form1" method="POST" action="contactForm2.php">
<p> </p>
<p>
<div id = "borderStyle">
<label>Your Name:
<input type="text" name="Name" id="textfield" required>
</p>
<br><br>
<p>Your Email:
<input type="text" name="Email Address" id="textfield2" required>
</p>
<br><br>
<p>Your Address:
<input type = "text" name = "address" id = "living">
</p>
<br><br>
<p>Reason for contact:
<select name="Reason" id="select2" onChange = "showProductProblemComments()" required>
<option value="default">Please Select a Reason</option>
<option value="product">Product Problem</option>
<option value="return">Return a Product</option>
<option value="billing">Billing Question</option>
<option value="technical">Report a Website Problem</option>
<option value="other">Other</option>
</select>
</p>
<br><br>
<p>Comments:
<textarea name="comments" id="textarea" cols="45" rows="5"required></textarea>
</p>
<br><br>
<p>
<input type="checkbox" name="Mailing List" id="checkbox" onClick = "showMailingListForm()">
Please put me on your mailing list.
</p>
<div id = "mailingInformation">
<h3>Please fill out the form below to be put on the mailing list to recieve coupons and special offers</h3>
<p>Check the box to use address above
<input type = "checkbox" name = "checkForAddress" id = "checkAddress">
</p>
<p>First Name:
<input type = "text" name = "mailingName" id = "mailing">
</p>
<p>Last Name:
<input type = "text" name = "mailingLastName" id = "mailingLast">
</p>
<p>Mailing Address:
<input type = "text" name = "mailingAddress" id = "mailingAdd">
</p>
<p>Phone Number(Optional)
<input type = "text" name = "phoneNumber" id = "phone">
</p>
</div>
<p>
<input type="checkbox" name="More Info" id="checkbox2">
Send me more information about your products.</label>
</p>
<br><br>
<p>
<input type="hidden" name="hiddenField" id="hidden" value="application-id:US447">
</p>
<br><br>
<p>
<input type="submit" name="button" id="button" value="Submit">
<input type="reset" name="button2" id="button2" value="Reset">
</p>
<div>
</form>
<div id = "hiddenStuff">
<p>
<table border='a'>
<tr>
<th>Field Name</th>
<th>Value of Field</th>
</tr>
<?php echo $tableBody; ?>
</table>
<!--</p>
<p>Name: <?php echo $inName; ?></p>
<p>Email: <?php echo $inEmail; ?></p>
<p>Address: <?php echo $inAddress; ?></p>
<p>Reason: <?php echo $inReason; ?></p>
<p>Comments: <?php echo $inComments; ?></p>
<p>Mailing List: <?php echo $inMailBox; ?></p>
<p>Use Previous Address Given: <?php echo $inUseAddress; ?></p>
<p>First Name: <?php echo $inFirstName; ?></p>
<p>Last Name?: <?php echo $inLastName; ?></p>
<p>Mailing Address: <?php echo $inMailingAdd; ?></p>
<p>Phone Number: <?php echo $inPhoneNumber; ?></p>
<p>More Information: <?php echo $inMoreInfo; ?></p>-->
</div>
</body>
</html>
Some line of code have been commented out for the sake of experimenting. Thank you in for the help.
That's because of this:
<?php
$toEmail = "robinjennings#nephilim42.com"; //CHANGE within the quotes. Place email address where you wish to send the form data.
//Use your DMACC email address for testing.
//Example: $toEmail = "jhgullion#dmacc.edu";
$subject = "WDV341 Email Example"; //CHANGE within the quotes. Place your own message. For the assignment use "WDV101 Email Example"
$fromEmail = "robinjennings#nephilim42.com"; //CHANGE within the quotes. Use your DMACC email address for testing OR
//use your domain email address if you have Heartland-Webhosting as your provider.
//Example: $fromEmail = "contact#jhgullion.org";
// DO NOT CHANGE THE FOLLOWING LINES //
$emailBody = "Form Data\n\n "; //stores the content of the email
foreach($_POST as $key => $value) //Reads through all the name-value pairs. $key: field name $value: value from the form
{
$emailBody.= $key."=".$value."\n"; //Adds the name value pairs to the body of the email, each one on their own line
}
$headers = "From: $fromEmail" . "\r\n"; //Creates the From header with the appropriate address
if (mail($toEmail,$subject,$emailBody,$headers)) //puts pieces together and sends the email to your hosting account's smtp (email) server
{
echo("<p>Message successfully sent!</p>");
}
else
{
echo("<p>Message delivery failed...</p>");
}
?>
You have to check if your form is submitted then the above code executes. So put the above code in:
if( isset($_REQUEST['form_element_index']) )
{
// Above code here
// Now the code executes when form is submitted
}
Its happening because you have't created a form and asked user to give input.What you have to do is create a form and then retreive the form values and upon submitting the form send the mail.It would definitely work....

Form's embedded jQuery Validate link creates an issue sending email, but if creates other issues if moved within file

I am using a form that is validated with jQuery Validate and general validation.
Currently, I am having two issues:
The hierarchy of my files that have been embedded on my page are as follows:
(1) PHP
(2) jquery-1.11.3.js
(3) jquery.validate.js
(4) jQuery Validation Scripts
Issue (A) is that although the fields are correctly validated and the 'red' class is added to all incorrect input fields, the email sends but the success message doesn't appear.
If I change the hierarchy of the embedded files to:
(1) PHP
(2) jquery-1.11.3.js
(4) jQuery Validation Scripts
(3) jquery.validate.js
Issue (B) I get is that although the fields are correctly validated, the 'red' class no longer gets added to any of the input fields. Also, the success message now appears but the form sends an email that has no inputted data.
How do I get around these issues so that the form works the way it should (in Issue A) but sends an email with the data in its message?
So to clarify, I want the form to work the way it is in Issue (A), the problem is that the email is being sent blank. But if I change the hierarchy of the embedded files, the email now sends the data but the success message doesn't appear.
Thanks.
HTML
<div id="after_submit"></div>
<form id="contact_form" action="" method="POST" enctype="multipart/form-data">
<div id="form-container" class="row form-input-group">
<input id="name" class="input required" name="name" type="text" value="" size="30"/><br />
</div>
<div id="form-container" class="row form-input-group">
<input id="email" class="input required" name="email" type="email" value="" size="30"/><br />
</div>
<div id="form-container" class="row form-input-group">
<input id="telephone" class="input" name="telephone" type='tel'><br />
</div>
<div id="form-container" class="row form-input-group">
<input id="event_date" class="input required" name="event_date" type="text" value="" size="30"/><br />
</div>
<div id="form-container" class="row form-input-group">
<input id="guests" class="input required" name="guests" type="text" value="" size="30"/><br />
</div>
<div id="form-container" class="row form-input-group">
<input id="hear_about" class="input required" name="hear_about" type="text" value="" size="30"/><br />
</div>
<div id="form-container" class="row form-input-group">
<textarea id="message" class="input required" name="message" rows="7" cols="30"></textarea><br />
</div>
<input id="submit_button" type="submit" value="Send email" />
</form>
PHP
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$subject = 'Website Contact Form Submission';
$message = "
<html>
<head>
</head>
<body>
<table>
<tr><td>Name:</td><td style=\"color: red;\"> ".$_POST["name"]."</td></tr>
<tr><td>Email:</td><td style=\"color: red;\"> ".$_POST["email"]."</td></tr>
<tr><td>Telephone:</td><td style=\"color: red;\"> ".$_POST["telephone"]."</td></tr>
<tr><td>Event Date:</td><td style=\"color: red;\"> ".$_POST["event_date"]."</td></tr>
<tr><td>Guests Amount:</td><td style=\"color: red;\"> ".$_POST["guests"]."</td></tr>
<tr><td>Hear About:</td><td style=\"color: red;\"> ".$_POST["hear_about"]."</td></tr>
<tr><td>Message:</td><td style=\"color: red;\"> ".$_POST["message"]."</td></tr>
</table>
</body>
</html>
";
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
$headers .= "From: ".$_POST["name"]." <".$_POST["email"].">\r\n";
$headers .= "Reply-To: ".$_POST["name"]." <".$_POST["email"].">\r\n";
mail("example#example.com",$subject,$message,$headers);
$nameErr = $emailErr = $telephoneErr = $hear_aboutErr = $messageErr = "";
$name = $email = $telephone = $event_date = $guests = $hear_about = $message = "";
$name = $_POST['name']; // required
$email = $_POST['email']; // required
$telephone = $_POST['telephone']; // not required
$event_date = $_POST['event_date']; // not required
$guests = $_POST['guests']; // not required
$hear_about = $_POST['hear_about']; // required
$message = $_POST['message']; // required
// required
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
}
// required
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
// not required
if (empty($_POST["telephone"])) {
$telephoneErr = "Incorrect telephone format";
} else {
$telephone = test_input($_POST["telephone"]);
// check if telephone is well-formed
if ( preg_match( '/^[+]?([\d]{0,3})?[\(\.\-\s]?([\d]{3})[\)\.\-\s]*([\d]{3})[\.\-\s]?([\d]{4})$/', $string ) ) {
$telephoneErr = "Invalid telephone format";
}
}
// not required
if (empty($_POST["event_date"])) {
$event_date = "";
} else {
$event_date = test_input($_POST["event_date"]);
}
// not required
if (empty($_POST["guests"])) {
$guests = "";
} else {
$guests = test_input($_POST["guests"]);
}
// required
if (empty($_POST["hear_about"]) < 5) {
$hear_aboutErr = "Please let us know where you heard about us";
} else {
$hear_about = test_input($_POST["hear_about"]);
}
// required
if (empty($_POST["message"]) < 5) {
$messageErr = "Not enough characters";
} else {
$message = test_input($_POST["message"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
}
?>
OTHER JQUERY VALIDATIONS
$(document).ready(function(){
debug: true,
$("#contact_form").validate({
rules: {
name: {
required: true,
minlength: 5,
letters : true,
},
email: {
email: true,
},
telephone: {
required: false,
digits: true,
minlength: 10,
},
message: {
required: true,
minlength: 5,
}
},
messages: {
name: {
required: "Please enter a name",
minlength: "Name is not long enough",
letters: "Please enter characters only"
},
email: {
required: "Please enter a valid email address"
},
message: {
required: "Please enter a message",
minlength: "Please enter at least 5 characters"
},
telephone: {
digits: "Please enter a valid phone number",
minlength: "Phone number is not long enough"
}
},
errorElement : 'span',
errorClass:'error',
validClass:'success',
highlight: function (element, errorClass, validClass) {
$(element).parents("#form-container").addClass(errorClass).removeClass(validClass);
},
unhighlight: function (element, errorClass, validClass) {
$(element).parents("#form-container").removeClass(errorClass).addClass(validClass);
},
});
var errors = false;
$('.required').parent().find('.input').on('blur', function() {
var field_container = $(this).parent();
if (!$.empty_field_validation($(this).val())) {
errors = true;
} else {
field_container.removeClass('error');
errors = false;
}
});
$('#name').on('blur', function(){
var field_container = $(this).parent();
if (!$.empty_field_validation($(this).val())) {
$("#name").addClass("red");
errors = true;
} else {
$("#name").removeClass("red");
errors = false;
}
});
$('#message').on('blur', function(){
var field_container = $(this).parent();
if (!$.empty_field_validation($(this).val())) {
$("#message").addClass("red");
errors = true;
} else {
$("#message").removeClass("red");
errors = false;
}
});
$('#email').on('blur', function(){
var field_container = $(this).parent();
if (!$.email_validation($(this).val())) {
$("#email").addClass("red");
errors = true;
} else {
$("#email").removeClass("red");
errors = false;
}
});
$('#telephone').on('blur', function(){
var field_container = $(this).parent();
if (!$.tel_validation($(this).val())) {
$("#telephone").addClass("red");
errors = true;
} else {
$("#telephone").removeClass("red");
errors = false;
}
});
$('#contact_form').submit(function(event) {
event.preventDefault();
$('.required').parent().find('.input').trigger('blur');
if (!errors)
$.ajax({
url: "index.php",
data: {
json: JSON.stringify($(this).serializeObject())
},
type: 'post',
success: function(data) {
var message = 'Hi '+data.name+'. Your message was sent and received.';
$('#after_submit').html(message);
$('#after_submit').css('display', 'block');
},
error: function() {
var message = 'Hi '+data.name+'. Your message could not be sent or received. Please try again later';
$('#after_submit').html(message);
$('#after_submit').css('display', 'block');
}
});
});
});
$.empty_field_validation = function(field_value) {
if (field_value.trim() == '') return false;
return true;
}
$.validator.addMethod('letters', function(value) { //Custom Method Validator
return value.match(/^[- a-zA-Z]+$/);
});
$.email_validation = function(email) {
var regex = /^([a-zA-Z0-9_.+-])+\#(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
return regex.test(email);
}
$.tel_validation = function(telephone) {
var regex = /^\d{3}(?: ?\d+)*$/;
return regex.test(telephone);
}
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
CSS
body{
width: 414px;
font-family: Arial;
font-size: 14px;
}
#after_submit, #email_validation, #name_validation {
display:none;
}
#after_submit{
background-color: #c0ffc0;
line-height: 31px;
margin-bottom: 10px;
padding-left: 20px;
-webkit-border-radius: 3px;
-moz-border-radius: 3px;
border-radius: 3px;
}
label, #after_submit{
color: #6c6c6c;
}
input{
line-height: 31px;
}
input, textarea{
width: 288px;
-webkit-border-radius: 3px;
-moz-border-radius: 3px;
border-radius: 3px;
background-color: rgba(255,255,255,.6);
border: solid 1px #b6c7cb;
}
#contact_form{
height: 317px;
background-color: #e1e9eb;
border: solid 1px #e5e5e5;
padding: 10px 20px 50px 20px;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border-radius: 5px;
}
#submit_button{
width: 109px;
height: 34px;
-webkit-border-radius: 3px;
-moz-border-radius: 3px;
border-radius: 3px;
background-color: #86c5fa;
-webkit-box-shadow: inset 0 2px rgba(255,255,255,.29);
-moz-box-shadow: inset 0 2px rgba(255,255,255,.29);
box-shadow: inset 0 2px rgba(255,255,255,.29);
border: solid 1px #77a4cb;
font-weight: bold;
color: #fff;
margin-left: 7px;
}
label.required:after {
content:'*';
color:#cb2027;
}
.red {
color: #cb2027;
border: 1px solid #cb2027;
}
.error_message{
font-style: italic;
font-size: 10px;
}
.row {
margin:5px;
}
#email-error, #message-error, #name-error, #telephone-error {
background: #fff none repeat scroll 0 0;
border: medium none;
color: #cb2027;
display: block;
float: left;
margin-left: auto;
margin-right: auto;
padding: 8px;
width: 288px;
}

how to validate my form using javascript [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
i want to validate my form using javascript .before the form submission,i want the server to display the error (if any)below the field input..how can i do dis in this code using external javascript file??
Here is my code:
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
.label_text {
float: left;
width: 44%;
text-align:right;
font-weight:bold;
color:purple;
}
.register1{
text-align:center;}
.header_tag{text-align:center;
font-weight:bold;
color:green;}
.header_tag1{ margin:10px;
float:left;
text-align:center;
font-weight:bold;
color:green}
.register_section{border:1px solid black;
text-align:center;
padding:20px;
margin-left:30%;
margin-right:30%;
float:none;
height:350px;
}
.input{ text-align:left;
float:left;
border:2px solid black;
}
.gender{float:left;}
.register{ float:left;
text-align:center;
color:green;
font-weight:bold;
padding:10px;
margin-left:36%;}
</style>
</head>
<body>
<?php
// define variables and set to empty values
$nameErr = $passwordErr = $password2Err = $emailErr = $genderErr = "";
$name = $password = $confirmpassword = $email = $gender = $description = "";
$result="";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$username = "";
$password = "";
$hostname = "";
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
//select a database to work with
$selected = mysql_select_db("test",$dbhandle)
or die("Could not select test");
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["password"])) {
$passwordErr = "Password is required";
} else {
$password = test_input($_POST["password"]);
}
if (empty($_POST["confirmpassword"])) {
$password2Err = "Confirm Password";
} else {
$password = test_input($_POST["confirmpassword"]);
}
if ($_POST['password']!= $_POST['confirmpassword'])
{
echo("Oops! Password did not match! Try again. ");
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
if (empty($_POST["description"])) {
$comment = "";
} else {
$comment = test_input($_POST["description"]);
}
if (empty($_POST["gender"])) {
$genderErr = "Gender is required";
} else {
$gender = test_input($_POST["gender"]);
}
if (empty($genderErr))
{if (empty($emailErr)){
if (empty($password2Err)){
if (empty($passwordErr)){
if (empty($nameErr)){
$result=mysql_query("SELECT * FROM person WHERE username ='$name' AND password='$password'AND Email='$email'");
if (mysql_num_rows($result)==0 )
{ // IF no previous user is using this username.
$result1=mysql_query("INSERT INTO person(username,password,Email,Gender) VALUES ( '$name', '$password','$email','$gender')");
{ if($result1)
////If the Insert Query was successfull.
// Send an email
// Finish the page:
{
echo '<div class="success">Thank you for registering! A confirmation email has been sent to ' . $email . ' </div>';
}
else
{ // If it did not run OK.
echo '<div class="errormsgbox">You could not be registered due to a system error. We apologize for any inconvenience.</div>';
}
}
}
// The username is not available.
else
{ echo '<div class="errormsgbox" >That username has already been registered.</div>';
}
}
}
}
}
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<div class="register1">
<h2 class="header_tag">REGISTER HERE</h2>
<p><span class="error"></span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<div class="register_section">
<div class="label_text">
Name:<span class="error">* </div>
<div class="input">
<input type="text" name="name"><br> </div>
<span class="error"><?php echo $nameErr;?></span>
<br><br>
<div class="label_text">
Password:<span class="error">* </div>
<div class="input">
<input type="text" name="password"><br> </div>
<span class="error"><?php echo $passwordErr;?></span>
<br><br>
<div class="label_text">
Confirm Password:<span class="error">* </div>
<div class="input">
<input type="text" name="confirmpassword"><br> </div>
<span class="error"><?php echo $password2Err;?></span>
<br><br>
<div class="label_text">
E-mail:<span class="error">* </div>
<div class="input">
<input type="text" name="email"><br></div>
<span class="error"><?php echo $emailErr;?></span>
<br><br>
<div class="label_text">
Description: </div>
<div class="input">
<textarea name="description" rows="5" cols="22"></textarea> </div>
<br><br>
<div class="label_text">
Gender:<span class="error">* </div>
<div class="gender">
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male
</div>
<span class="error"><?php echo $genderErr;?></span>
<br><br><br>
<div class="register">
<input type="submit" name="submit" value="REGISTER">
<br>
<h3 class="header_tag1">"Back to Login
</div>
</div>
</div>
</form>
</body>
</html>
What you are trying to do is properly called client-side validation.
The easiest way to do this would be to use a third-party library, such as FormValidation.
For example, to validate your email field, you could do something like:
<form method="post" id="register_user" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
...
<input type="text" name="email" data-fv-emailaddress="true" data-fv-emailaddress-message="The value is not a valid email address" />
...
</form>
<script>
$('#register_user').submit(function() {
$('#register_user').formValidation();
});
</script>
Of course, you'll need to make sure to include the necessary CSS and JS libraries for jQuery, FormValidation, and a suitable content framework (such as Bootstrap).
For the record, if you're just looking for a basic user management script, I would strongly suggest that you avoid reinventing the wheel. Take an existing script, for example UserFrosting, and modify it to suit your needs.

Clear input with submit button

Switching over from C# to PHP for a bit and not seeing what I am doing wrong here.
What I am wanting to to is when I click the submit button - I want the email sent (like it is doing) but then I want the input text fields to clear out the old text the user had previously input.
The one way I had it figured out would clear my test before it was actually submitted, which didn't help me very much.
Any input on how to do this?
<?php
/*
* Template Name: Contact
* Description: Contact Us
*/
get_header();
?>
<div class="container">
<div class="section group">
<div class="col span_2_of_2">
<h1> Contact Us <h1>
<p style="font-size:16px"> Radiology Services LLC is located on the east side of Evansville, IN off the Robert D. Orr Highway.</p>
<iframe src="https://www.google.com/maps/embed?pb=!1m14!1m8!1m3!1d3146.027108890167!2d- 87.45272299999999!3d37.953153!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x0%3A0x170f5925d75e6135!2s Radiology+Services+LLC!5e0!3m2!1sen!2sus!4v1404175203674" width="100%" height="350px" frameborder="0" style="border:0"></iframe>
</div>
<div class="col span_1_of_2" style="padding-left:40px;>
<?php
//response generation function
$response = "";
//function to generate response
function my_contact_form_generate_response($type, $message){
global $response;
if($type == "success") $response = "<div class='success'>{$message}</div>";
else $response = "<div class='error'>{$message}</div>";
}
//response messages
$not_human = "Human verification incorrect.";
$missing_content = "Please supply all information.";
$email_invalid = "Email Address Invalid.";
$message_unsent = "Message was not sent. Try Again.";
$message_sent = "Thanks! Your message has been sent.";
//user posted variables
$name = $_POST['message_name'];
$email = $_POST['message_email'];
$message = $_POST['message_text'];
$human = $_POST['message_human'];
//php mailer variables
$to = 'aje#gmail.com';
$subject = "Someone sent a message from ".get_bloginfo('name');
$headers = 'From: '. $email . "\r\n" .
'Reply-To: ' . $email . "\r\n";
if(!$human == 0){
if($human != 2) my_contact_form_generate_response("error", $not_human); //not human!
else {
//validate email
if(!filter_var($email, FILTER_VALIDATE_EMAIL))
my_contact_form_generate_response("error", $email_invalid);
else //email is valid
{
//validate presence of name and message
if(empty($name) || empty($message)){
my_contact_form_generate_response("error", $missing_content);
}
else //ready to go!
{
$sent = wp_mail($to, $subject, strip_tags($message), $headers);
if($sent) my_contact_form_generate_response("success", $message_sent);
else my_contact_form_generate_response("error", $message_unsent);
}
}
}
}
else if ($_POST['submitted']) my_contact_form_generate_response("error", $missing_content);
?>
<?php while ( have_posts() ) : the_post(); ?>
<div class="entry-content">
<?php the_content(); ?>
<style type="text/css">
.error{
padding: 5px 9px;
border: 1px solid red;
color: red;
border-radius: 3px;
}
.success{
padding: 5px 9px;
border: 1px solid green;
color: green;
border-radius: 3px;
}
form span{
color: red;
}
.subBtn{
width:100%;
border-radius: 0px;
background-color:#5bb75b;
color:#FFFFFF;
}
.subBtn:hover{
background-color:#408140;
}
.m{
width:100%;
border-radius: 0px;
}
</style>
<script language="javascript">
fromreset()
{
myform.reset();
document.myform.[textbox Id] = " ";
}
</script>
<form name="myform" id="myform"action="<?php the_permalink(); ?>" method="post">
<label for="name" class="m">Name: <span>*</span> <br>
<input type="text" class="m" id="name" name="message_name" value="<?php echo esc_attr($_POST['message_name']); ?>">
</label>
<label for="message_email" class="m">Email: <span>*</span> <br>
<input type="text" class="m" id="email" name="message_email" value="<?php echo esc_attr($_POST['message_email']); ?>">
</label>
<label for="message_text" class="m" id="mu">Message: <span>*</span> <br>
<textarea type="text" class="m" id="textm" name="message_text"><?php echo esc_textarea($_POST['message_text']); ?></textarea>
</label>
<label for="message_human" class="m">Human Verification: <span>*</span> <br>
<input type="text" class="m" name="message_human"> + 3 = 5
</label>
<input type="hidden" name="submitted" value="1" class="m">
<input type="hidden" name="submitted" value="1" style="width:100%">
<input type="submit" value="submit" class="subBtn" onclick="formreset();">
<?php echo $response; ?>
</form>
</div>
</div>
<?php endwhile; // end of the loop. ?>
</div><!-- #content -->
</div>
<?php get_footer(); ?>

Categories

Resources