Simple form skips validation/sending and goings straight to ajax message - javascript

I have been following this tutorial to validate a form on a HTML5 template I am working on modifying. Here is the link: http://englishpearls.net/dev/contact.html
As you see, the form goes straight to the ajax message and skips everything else. What am I doing wrong?
HTML
<div id="contact_form">
<form method="post" action="contact-post.html" >
<div class="to">
<input id="name" for="name" type="text" class="text" value="Name" name="userName" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'Name';}">
<label class="error" for="name" id="name_error">This field is required.</label>
<input id="email" type="text" class="text" value="Email" name="userEmail" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'Email';}" style="margin-left: 10px">
<label for="email" class="error" for="email" id="email_error">This field is required.</label>
</div>
<div class="to">
<input id="phone" for="phone" type="text" class="text" value="Phone" name="userPhone" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'Phone';}">
<label class="error" for="phone" id="phone_error">This field is required.</label>
<input id="subject" type="text" class="text" value="Subject" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'Subject';}" style="margin-left: 10px">
<label class="error" for="subject" id="subject_error">This field is required.</label>
</div>
<div class="text">
<textarea id="message" value="Message:" name="userMsg" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'Message';}">Message:</textarea>
<label class="error" for="message" id="message_error">This field is required.</label>
</div>
<div>
<input class="button" type="submit" value="Submit" name="submit" />
</div>
</div>
Jquery EDIT: Updated Script
<script type="text/javascript">
$(function() {
$('.error').hide();
$(".button").click(function() {
// validate and process form here
$('.error').hide();
var name = $("input#name").val();
if (name == "") {
$("label#name_error").show();
$("input#name").focus();
return false;
}
var email = $("input#email").val();
if (email == "") {
$("label#email_error").show();
$("input#email").focus();
return false;
}
var phone = $("input#phone").val();
if (phone == "") {
$("label#phone_error").show();
$("input#phone").focus();
return false;
}
var subject = $("input#subject").val();
if (subject == "") {
$("label#subject_error").show();
$("input#subject").focus();
return false;
}
var message = $("input#message").val();
if (message == "") {
$("label#message_error").show();
$("input#message").focus();
return false;
}
var dataString = 'name='+ name + '&email=' + email + '&phone=' + phone + '&subject=' + subject + '&message=' + message;
//alert (dataString);return false;
$.ajax({
type: "POST",
url: "contact-post.html",
data: dataString,
success: function() {
$('#contact_form').html("<div id='message'></div>");
$('#message').html("<h2>Contact Form Submitted!</h2>")
.append("<p>We will be in touch soon.</p>")
.hide()
.fadeIn(1500, function() {
$('#message').append("<img id='checkmark' src='web/images/check.jpg' />");
});
}
});
return false;
});
});
</script>
Without the validation script, the email sends fine. Thanks!

The way your script is setup right now, the AJAX call will fire immediately, regardless of any input. It needs to be inside of this:
$(".button").click(function () {
}
function, which should have an if statement that will only allow the AJAX to fire if the validation of the form is successful.
Updated:
<div id="contact_form">
<form id="contact-post" method="post" action="contact-post.html" >
<div class="to">
<input id="name" for="name" type="text" class="text" placeholder="Name" name="userName" >
<label class="error" for="name" id="name_error">This field is required.</label>
<input id="email" type="text" class="text" placeholder="Email" name="userEmail" style="margin-left: 10px">
<label for="email" class="error" for="email" id="email_error">This field is required.</label>
</div>
<div class="to">
<input id="phone" for="phone" type="text" class="text" placeholder="Phone" name="userPhone" >
<label class="error" for="phone" id="phone_error">This field is required.</label>
<input id="subject" type="text" class="text" placeholder="Subject"style="margin-left: 10px">
<label class="error" for="subject" id="subject_error">This field is required.</label>
</div>
<div class="text">
<textarea id="message" placeholder="Message:" name="userMsg">Message:</textarea>
<label class="error" for="message" id="message_error">This field is required.</label>
</div>
<div>
<input class="button" type="submit" value="Submit" name="submit" />
</div>
JS:
<script type = "text/javascript">
$(function () {
$('.error').hide();
$("#contact-post").submit(function (event) {
alert("submitted");
event.preventDefault();
// validate and process form here
$('.error').hide();
var name = $("input#name").val();
var email = $("input#email").val();
var phone = $("input#phone").val();
var subject = $("input#subject").val();
var message = $("#message").val();
if (name == "") {
$("label#name_error").show();
$("input#name").focus();
} else if (email == "") {
$("label#email_error").show();
$("input#email").focus();
} else if (phone == "") {
$("label#phone_error").show();
$("input#phone").focus();
} else if (subject == "") {
$("label#subject_error").show();
$("input#subject").focus();
} else if (message == "") {
$("label#message_error").show();
$("input#message").focus();
} else {
var dataString = 'name=' + name + '&email=' + email + '&phone=' + phone + '&subject=' + subject + '&message=' + message;
$.ajax({
type: "POST",
url: "app/contact.php",
data: dataString,
success: function () {
$('#contact_form').html("<div id='message'></div>");
$('#message').html("<h2>Contact Form Submitted!</h2>")
.append("<p>We will be in touch soon.</p>")
.hide()
.fadeIn(1500, function () {
$('#message').append("<img id='checkmark' src='web/images/check.jpg' />");
});
}
});
}
});
});
< /script>
That will work. Also I changed all of the value attributes in your HTML to placeholder attributes so they function as expected and don't get in the way of the validation.
Alternatively, since you're already using jQuery, you could check out jQuery Validate, a jQuery plugin that would make this much simpler
UPDATE:
I removed all of the onfocus/onblur attributes from your HTML and it works now. The JS in the onblur tags was filling the form with values, so it was able to pass validation. Look at this JSFIDDLE for a working verison
UPDATE 2:
The var message = $("input#message").val() should be var message = $("#message").val().
The first one is looking for an input with the id of "message", where as you have a textarea with that id. Changing this line will correct the blank message you're getting. (see the updated JS above)
Regarding this question,
I have noticed that in the first link I have the $(".button").submit(function (event) whereas in your config, in the same spot you have $("#contact-post").submit(function (event)
I have the validation being performed when a form with the id of "contact-post" gets submitted, instead of when the button gets submitted (which isn't possible). The reason the page with this JS/form is submitting is that the JS to validate never gets triggered.
It's possible (although unlikely) to submit the form without clicking that button, so we don't want the validation to be skipped on the off-chance that happens.

You could try adding "return true;" to the .click
$(".button").click(function () {
//...
//validation code
//...
//return true if passes validation
return true;
}

Have you thought about combining things like this:
$('yourForm').on('submit', function(event){
if ( formIsvalid() ) {
$.ajax({
...
});
} else {
// Do something else maybe?
}
event.preventDefault();
});
// Form validation.
function formIsvalid() {
... form validation here...
return true;
}

Related

How can I add an animation on my HTML form when submit input is clicked and the input is empty on Javascript?

Basically, I'm coding a Javascript code that validate if a form is empty, so if one input is empty, it add an animation from Animate.css library. And if two inputs are empty, both will make the shake animation, if the whole form is empty, it will shake.
I've tried a global function with conditions that add a class and it doesn't work.
This is my form:
<form action="" id="form">
<label for="name">Name</label>
<input
type="text"
placeholder="Name"
id="name"
minlength="3"
required
/>
<br />
<label for="email">Email</label>
<input type="email" placeholder="Emai" id="email" required />
<br />
<label for="subject">Subject</label>
<input
type="text"
placeholder="Subject"
id="subject"
minlength="3"
required
/>
<br />
<label for="message">Message</label>
<textarea
name="message"
id="message"
minlength="5"
placeholder="Message"
required
style="resize: none; height: 200px"
></textarea>
<br />
<button type="submit" class="paper-btn" id="submit">
Send message
</button>
</form>
Javascript:
(function () {
var form = document.getElementById("form"),
name = form.name,
email = form.email,
subject = form.subject;
message = form.message;
function validateName(e) {
if (name.value == "" || name.value == null) {
form.classList.add("animate__animated");
name.classList.add("animate__shakeX");
e.preventDefaul();
} else {
console.log("error");
}
}
function validateEmail(e) {
if (email.value == "" || email.value == null) {
email.classList.add("animate__animated");
email.classList.add("animate__shakeX");
e.preventDefaul();
}
}
function validateSubject(e) {
if (subject.value == "" || subject.value == null) {
subject.classList.add("animate__animated");
subject.classList.add("animate__shakeX");
e.preventDefaul();
}
}
function validateMessage(e) {
if (subject.value == "" || subject.value == null) {
message.classList.add("animate__animated");
message.classList.add("animate__shakeX");
e.preventDefaul();
}
}
function validateForm(e) {
validateName(e);
validateEmail(e);
validateSubject(e);
validateMessage(e);
}
form.addEventListener("submit", validateForm);
});
I think you just need to invoke the function. ValidateForm isn't being called
(function() {
var name = document.getElementById("name");
if (name.value == "" || name.value == null) {
name.classList.add("animate__animated");
name.classList.add("animate__shakeX");
}
})();

Contact Form Sending message even if captcha not correct

I am trying to implement a Contact from with custom Captcha using PHPmailer. The contact form works fine. The PHPmailer works fine as well. To avoid a lot of spam letters, I decided to implement custom Captcha, the problem is that the emails go anyway captcha is correct or incorrect.
<h4 class="sent-notification"></h4>
<form id="myForm">
<p>
<label>Name<span style="color:#ff0000; margin-left:5px;">*</span></label>
<input id="name" type="text" name="name" required>
</p>
<p>
<label>Company<span style="color:#ff0000; margin-left:5px;">*</span></label>
<input id="subject" type="text" name="company" required>
</p>
<p>
<label>Email<span style="color:#ff0000; margin-left:5px;">*</span></label>
<input id="email" type="email" name="email" required>
</p>
<p class="full">
<label>Message<span style="color:#ff0000; margin-left:5px;">*</span></label>
<textarea id="body" name="message" rows="5" required></textarea>
</p>
<div class="contain">
<input type="text" id="capt" readonly="readonly">
<div id="refresh"> <img src="assets/img/icons/refresh.png" alt="refresh" width="50px" onclick="cap()"></div>
<input type="text" id="textinput" placeholder="Refresh to type Captcha" required>
<button onclick="validcap()">Check</button>
</div>
<p>
<button class="full" onclick="sendEmail()" value="Send An Email">Submit</button>
</p>
</form>
Script for PHPmailer
<script type="text/javascript">
function sendEmail() {
var name = $("#name");
var email = $("#email");
var subject = $("#subject");
var body = $("#body");
var textinput = $("#textinput");
if (isNotEmpty(name) && isNotEmpty(email) && isNotEmpty(subject) && isNotEmpty(body) && isNotEmpty(textinput)) {
$.ajax({
url: 'sendEmail.php',
method: 'POST',
dataType: 'json',
data: {
name: name.val(),
email: email.val(),
subject: subject.val(),
body: body.val(),
textinput: textinput.val()
}, success: function (response) {
$('#myForm')[0].reset();
$('.sent-notification').text("Message Sent Successfully");
}
});
}
}
function isNotEmpty(caller) {
if (caller.val() == "") {
caller.css('border', '1px solid red');
return false;
} else
caller.css('border', '');
return true;
}
</script>
Script for Captcha
<script type="text/javascript">
function cap() {
var alpha=['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V'
,'W','X','Y','Z','1','2','3','4','5','6','7','8','9','0','a','b','c','d','e','f','g','h','i',
'j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'];
var a=alpha[Math.floor(Math.random()*62)];
var b=alpha[Math.floor(Math.random()*62)];
var c=alpha[Math.floor(Math.random()*62)];
var d=alpha[Math.floor(Math.random()*62)];
var e=alpha[Math.floor(Math.random()*62)];
var f=alpha[Math.floor(Math.random()*62)];
var sum=a + b + c + d + e + f;
document.getElementById("capt").value=sum;
}
function validcap() {
var string1 = document.getElementById('capt').value;
var string2 = document.getElementById('textinput').value;
if (string1 == string2){
alert("Form is validated Succesfully");
return true;
}
else {
alert("Please enter a valid captcha");
return false;
}
}
</script>

The onsubmit event handler javascript not working

I have a problem. When I clicked the submit button nothing happens, even when I filled out the username and password with numbers (I don't want the username and password contains any number so I did make the condition for it), there is no alert display. I do not know where the problem comes from? Can you guys help me with this
Note: the reset function works fine
function validateInput() {
var firstName = document.forms["sign_up"]["firstName"];
var lastName = document.forms["sign_up"]["lastName"];
var email = document.forms["sign_up"]["email"];
var reg = /^[a-zA-Z]+$/;
if (firstName.value !== '' || lastName.value !== '' || email.value !== '') {
if (firstName.value.match(reg) && lastName.value.match(reg)) {
alert("Form is submitted");
// return true;
return false; // for the demo, so it doesn't submit
} else {
if (firstName.value.match(reg) === false) {
document.getElementById("error").innerHTML = "Numbers are not allowed in username";
return false;
} else if (lastName.value.match(reg) === false) {
document.getElementById("error").innerHTML = "Numbers are not allowed in password";
return false;
}
}
}
}
function reset() {
document.getElementById("first").innerHTML = "";
document.getElementById("last").innerHTML = "";
document.getElementById("email").innerHTML = "";
}
<form id="sign_up" onsubmit="return validateInput()">
<p id="error"></p>
<label for="firstName">First Name</label>
<input type="text" id="firstName" value="" placeholder="Enter your first name">
<label for="lastName">Last Name</label>
<input type="text" id="lastName" value="" placeholder="Enter your last name">
<label for="email">Email</label>
<input type="email" id="email" value="" placeholder="Enter your email">
<button type="submit">Submit</button>
<button type="button" onclick="reset();">Cancel</button>
</form>
Use the Pattern attribute in input for validation like below
<input type="text" id="firstName" value="" pattern="[^0-9]*" title="Numbers are not allowed" placeholder="Enter your first name">
for more references: https://www.w3schools.com/tags/att_input_pattern.asp
And for reset functionality use reset
<input type="reset" value="reset">
It's better than create a special function for it and it saves your number of lines:-)
First, try to avoid to inline event handlers as they are not rec-emended at all. Also to reset form values you can simply use reset() method on the form.
Also, do not use innerHTML just to set the text of your error. You can use textContent instead which is better fit in your example.
You can use addEventListener with submit event to check for validation on your firstname and lastname.
I have fixed your code and its all working as expected.
Live Working Demo:
let form = document.getElementById("sign_up")
var firstName = document.getElementById("firstName")
var lastName = document.getElementById("lastName")
var email = document.getElementById("email")
var reset = document.getElementById("clearValues")
var reg = /^[a-zA-Z]+$/;
form.addEventListener('submit', function(e) {
e.preventDefault()
if (firstName.value != '' || lastName.value != '' || email.value != '') {
if (firstName.value.match(reg) && lastName.value.match(reg)) {
alert("Form is submitted");
} else if (!firstName.value.match(reg)) {
document.getElementById("error").textContent = "Numbers are not allowed in username";
} else if (!lastName.value.match(reg)) {
document.getElementById("error").textContent = "Numbers are not allowed in password";
}
}
})
reset.addEventListener('click', function(e) {
document.getElementById("sign_up").reset();
})
input {
display:block;
}
<head>
</head>
<body>
<form id="sign_up" action="#">
<p id="error"></p>
<label for="firstName">First Name</label>
<input type="text" id="firstName" value="" placeholder="Enter your first name">
<label for="lastName">Last Name</label>
<input type="text" id="lastName" value="" placeholder="Enter your last name">
<label for="email">Email</label>
<input type="email" id="email" value="" placeholder="Enter your email">
<button type="submit">
Submit
</button>
<button type="button" id="clearValues" onclick="reset();">
Cancel
</button>
</form>
</body>
You don't need to return a function in onsubmit event. This should work fine.
<form id="sign_up" onsubmit="validateInput()">
Reference:
https://www.w3schools.com/jsref/event_onsubmit.asp

JQuery HTML form validation still triggers email with blank entries

I have an HTML form with three mandatory fields in. I don't want the form to submit the AJAX call if they are empty.
$("#contact").submit(function(e){
e.preventDefault();
var ajaxurl = '<?php echo WEB_URL; ?>contact_send.php';
var data = $(this).serializeArray();
console.log(data);
var valid = true;
if( $('input[name="Name"]').val() == '' || $('input[name="Email"]').val() == '' || $('input[name="Phone"]').val() == '') {
valid = false;
}
if(valid) {
$.post(ajaxurl, data, function (response) {
$(".show_homecontact_form_success").fadeIn(1000);
$("#contact")[0].reset();
});
} else {
alert('Please fill in all mandatory fields.');
}
});
<form id="contact" name="contact" method="post" action="">
<label for="Name">Name: *</label>
<input type="text" name="Name" id="name" />
<input name="robotest" type="hidden" value="" />
<label for="Position">Position:</label>
<input type="text" name="Position" id="position" />
<label for="Company">Company:</label>
<input type="text" name="Company" id="company" />
<label for="Address">Address:</label>
<input type="text" name="Address" id="address" />
<label for="Email">Email: *</label>
<input type="text" name="Email" id="email" />
<label for="Email">Phone number: *</label>
<input type="text" name="Phone" id="phone" />
<label for="Event_Subject">What is the subject of the event?:</label>
<input type="text" name="Event_Subject" id="subject" />
<label for="Event_Date">What is the date of the event?:</label>
<input type="text" name="Event_Date" id="date" />
<label for="Additional_info">Additional Information:</label>
<br />
<textarea name="Additional_info" rows="20" cols="20" id="info"></textarea>
<input id="formsubmitted" type="submit" name="submit" value="submit" class="submit-button" />
</form>
This does give the popup box if you try and fill it in empty, but I have received an email with all blank fields.
How is the user getting past the validation and managing to send the form through blank?
More than likely you've not popped in a preventDefault() in there, so the form is doing a normal (non-AJAX) post after your function ends. What's the method/action on your form? Perhaps there doesn't need to be an action at all?
Try this:
$("#contact").submit(function(e){
e.preventDefault();
var ajaxurl = '<?php echo WEB_URL; ?>contact_send.php';
var data = $(this).serializeArray();
console.log(data);
var valid;
if( $('input[name="Name"]').val().length > 0
&& $('input[name="Email"]').val().length > 0
&& $('input[name="Phone"]').val().length > 0) {
valid = true;
} else {
valid = false;
}
if(valid) {
$.post(ajaxurl, data, function (response) {
$(".show_homecontact_form_success").fadeIn(1000);
$("#contact")[0].reset();
});
} else {
alert('Please fill in all mandatory fields.');
}
});
As Jigar pointed out, you can shorten the code by assigning an initial value to the valid variable and removing else block:
var valid = false;
if( $('input[name="Name"]').val().length > 0
&& $('input[name="Email"]').val().length > 0
&& $('input[name="Phone"]').val().length > 0) {
valid = true;
}

Can't insert spaces in my text input

I have a form with 3 text inputs, the problem is, when I want to insert a space it doesn't allow me to. My code is:
<form action="post.php" name="MYFORM" id="MYFORM" method="post">
<label>Name</label>
<input name="name" size="30" type="text" id="name">
<br clear="all" />
<label>Email</label>
<input name="email" size="30" type="text" id="email">
<br clear="all" />
<label>Message</label>
<textarea id="message" name="message"></textarea>
<br clear="all" /><br clear="all" />
<label> </label>
<input value="Send" type="submit" id="Send">
When it submits it is validated by a javascript file and afterwards mailed by a php file, but I dont think that matters.
PROBLEM: cant add spaces in these text inputs.
Thanx in advance
EDIT: JAVASCRIPT CODE:
$(document).ready(function() {
$('#Send').click(function() {
// name validation
var nameVal = $("#name").val();
if(nameVal == '') {
$("#name_error").html('');
$("#name").after('<div class="errorwrapper"><label class="error" id="name_error">Please enter your name.</label></div>');
return false
}
else
{
$("#name_error").html('');
}
/// email validation
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
var emailaddressVal = $("#email").val();
if(emailaddressVal == '') {
$("#email_error").html('');
$("#email").after('<div class="errorwrapper"><label class="error" id="email_error">Please enter your email address.</label></div>');
return false
}
else if(!emailReg.test(emailaddressVal)) {
$("#email_error").html('');
$("#email").after('<div class="errorwrapper"><label class="error" id="email_error">Enter a valid email address.</label></div>');
return false
}
else
{
$("#email_error").html('');
}
var mesVal = $("#message").val();
if(mesVal == '') {
$("#mes_error").html('');
$("#message").after('<div class="errorwrapper"><label class="error" id="mes_error">Please enter a message.</label></div>');
}
else
{
$("#after_submit").html('');
$("#Send").after('<label class="success" id="after_submit">Your message has been submitted.</label>');
$("#after_submit").fadeOut(9000);
$("#mes_error").html('');
clear_form();
}
return false;
})
function clear_form()
{
$("#name").val('');
$("#email").val('');
$("#message").val('');
$(".errorwrapper").empty();
}
});
I would have never figured it out if i wouldnt have seen an other person with an error in using a keyboard controlled javascript slideshow. Sry if i caused you guys wasting some time.
I was using fadeslideshow 2.0 by Pascal Bajorat.

Categories