creating a validation script for a submission form - javascript

I have created a submission form using Expression engine's plugin freeform, everything is working in terms of submission, the only issue i am having is the valuation side of things.
Is there a way to validate my script before submission, i.e pick up things as unfilled fields, incorrect emails etc..
below is a snippet of my code.
JQUERY
var form = $('#ajax-contact');
var formMessages = $('#form-messages');
$(form).submit(function(e) {
e.preventDefault();
var formData = $(form).serialize();
// Submit the form using AJAX.
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData
})
.done(function(response) {
if (response.success) {
formMessages.removeClass('error').addClass('success').text("Thank you for submitting your details");
$('.valFields').val("");
} else {
formMessages.removeClass("success").addClass("error").text("Oops, Please check your details");
}
})
.fail(function(data) {
// Make sure that the formMessages div has the 'error' class.
$(formMessages).removeClass('success');
$(formMessages).addClass('error');
// Set the message text.
if (data.responseText !== '') {
$(formMessages).text(data.responseText);
} else {
$(formMessages).text('Oops! An error occured and your message could not be sent.');
}
});
})
});
HTML
<div id="form-messages">
{exp:freeform:form
form_id="1"
admin_notify="myemail#.me.com"
form:class="main-contact submit-fade ajax-form"
form:id="ajax-contact"
}
<ul class="small-block-grid-2 medium-block-grid-2 hide-form">
<li>
<label for="name">Name</label>
{freeform:field:first_name
attr:class="form-control valFields"
attr:placeholder="First Name"
attr:class="required"
}
</li>
<li>
<label for="email">Email</label>
{freeform:field:email
attr:class="form-control valFields"
attr:placeholder="Email"
attr:class="required"
}
</li>
</ul>
<input type="submit" class="btn btn-success">
{/exp:freeform:form}
</div>
</div>
</div>

Validation of fields can done calling a function
Call Validate function onSubmit action and if successful perform the submission of form using AJAX.
Example:
<script>
$(form).submit(function(e) {
e.preventDefault();
var check = validate();
if(check){
var formData = $(form).serialize();
..
//form sumit using AJAX
..
}
function validate()
{
if( document.myForm.Name.value == "" )
{
alert( "Please provide your name!" );
document.myForm.Name.focus() ;
return false;
}
if( document.myForm.EMail.value == "" )
{
alert( "Please provide your Email!" );
document.myForm.EMail.focus() ;
return false;
}
return true;
}
</script>

The better way of doing this is putting types in inputs
<ul class="small-block-grid-2 medium-block-grid-2 hide-form">
<li>
<label for="name">Name</label>
{freeform:field:first_name
attr:class="form-control valFields"
attr:placeholder="First Name"
attr:required="required"
}
</li>
<li>
<label for="email">Email</label>
{freeform:field:email
attr:class="form-control valFields"
attr:placeholder="Email"
attr:required="required",
attr:type="email"
}
</li>
</ul>
It will not only make sure that the fields are not left empty but also will check the valid email type.

Related

Ajax validation no request send to server

I apologize for opening what might be a very basic post, I am learning Ajax please keep that in mind.
I have a simple registration form.
What im trying to do
validate the form
if all is in order register new user
I have managed to get the Ajax script to register a new user but my problem comes in with the validation part hench im turning here for a bit of help and advice
HTML
<div id="regResponse">
</div>
<form class="form-horizontal" id="regForm" role="form" method="post" action="../register.php" >
<div class="form-group">
<label class="control-label col-sm-2" for="regName">Name:</label>
<div class="col-sm-10">
<input type="text" name="regName" class="form-control" id="name" placeholder="">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="regLastName">Surname:</label>
<div class="col-sm-10">
<input type="text" name="regLastname" class="form-control" id="lastname" placeholder="">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="regEmail">Email:</label>
<div class="col-sm-10">
<input type="text" name="regEmail" class="form-control" id="regEmail" placeholder="">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="regPword">Pword:</label>
<div class="col-sm-10">
<input type="text" name="regPword" class="form-control" id="regPword" placeholder="">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="confRegPword">Confirm Pword:</label>
<div class="col-sm-10">
<input type="text" name="confRegPword" class="form-control" id="regPword2" placeholder="">
</div>
JQUERY AJAX
function sendForm() {
var valid;
valid = validateContact()
if(valid){
// Get the form.
var form = $('#regForm');
// Get the messages div.
var formMessages = $('#regResponse');
// Set up an event listener for the contact form.
$(form).submit(function(e) {
// Stop the browser from submitting the form.
e.preventDefault();
// Serialize the form data.
var formData = $(form).serialize();
// Submit the form using AJAX.
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData
})
.done(function(response) {
// Make sure that the formMessages div has the 'success' class.
$(formMessages).removeClass('error').addClass('success');
// Set the message text.
$(formMessages).html(response); // < html();
// Clear the form.
$('').val('')
})
.fail(function(data) {
// Make sure that the formMessages div has the 'error' class.
$(formMessages).removeClass('success').addClass('error');
// Set the message text.
var messageHtml = data.responseText !== '' ? data.responseText : 'Oops! An error occured and your message could not be sent.';
$(formMessages).html(messageHtml); // < html()
});
});
}
}
function validateContact(){
var valid = true;
var name = document.getElementById("name").value;
var lastname = document.getElementById("lastname").value;
var email = document.getElementById("regEmail").value;
if(name ==''){
document.getElementById("name").style.borderColor="red";
name.value="Please Enter Name";
valid = false;
}
if(lastname ==''){
valid = false;
}
if(email ==''){
valid = false;
}
return valid;
}
PHP
if ($_SERVER["REQUEST_METHOD"] == "POST") {
//get variables from reg form
$name = $_POST['regName'];
$lastName = $_POST['regLastname'];
$email = $_POST['regEmail'];
:
$sql ="INSERT INTO members......."
($result = mysql_query($sql) or trigger_error(mysql_error()."in".$sql);
if($result){
echo '<h3 style="blue">Registration Succesesfull</h3>';
}
else{
echo '<h3 style="blue">OOPS...Something went wrong here</h3>';
}
}//request POST method
Like I said as form the registration part all is working but as soon as I added the JavaScript validation the whole script stopped working. My biggest problem is that my browser is not showing me any errors so I dont know where I am going wrong
Any help will be much appreciated
Your sendForm function is not triggered.
Code below as your reference, is the right way to trigger submit event via jquery.
jQuery
$(function() {
$('form').submit(function(e) {
e.preventDefault();
var valid;
valid = validateContact()
if(valid ) {
$.ajax({
type: 'POST',
url: "http://facebook.com",
data: {},
dataType: 'json',
success: function() {
alert('success');
},
error: function() {
alert('error');
}
})
}
});
});
function validateContact(){
var valid = true;
var name = document.getElementById("name").value;
var lastname = document.getElementById("lastname").value;
var email = document.getElementById("regEmail").value;
if(name ==''){
document.getElementById("name").style.borderColor="red";
name.value="Please Enter Name";
valid = false;
}
if(lastname ==''){
valid = false;
}
if(email ==''){
valid = false;
}
return valid;
}
I think you need to add a button in your html and call function sendForm() on that button's click event.

Multiple AJAX forms with the same ID on the same page

I have two AJAX newsletter subscribe forms on the same page (top and bottom). Both forms have the same ID. The top form works perfectly, however I'm unable to get the alert messages to appear in the bottom form.
I found this question but wasn't sure how to implement the answer into my code.
Here's the form:
<div class="newsletter">
<form id="newsletter" class="newsletter-signup" action="" method="POST" accept-charset="UTF-8">
<input id="hero-section-newsletter-email-input" type="email" name="email">
<button class="button" type="submit">
Subscribe
</button>
<div id="newsletter-alert" style="display: none;" data-alert></div>
</form>
</div>
Here's the jQuery:
(function() {
'use strict';
var newsletterAlert = function(message) {
$('#newsletter-alert').text(message);
};
var isValidEmail = function(email) {
var pattern = new RegExp(/^[+a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/i);
return pattern.test(email);
};
$('#newsletter').on('submit', function(e) {
var data,
$form = $(this),
$email = $form.find('input[type="email"]');
e.preventDefault();
$('#newsletter-alert').show();
if ( !isValidEmail( $email.val() )) {
newsletterAlert('Looks like you entered an invalid email address! Please try again.');
} else {
newsletterAlert('Subscribing you now...');
data = $form.serialize();
$.ajax({
url: 'PATH_TO_SUBSCRIBE_PHP',
type: 'post',
data: data,
success: function(msg) {
if ( msg === 'success') {
newsletterAlert('Success! Please check your email to confirm.');
$email.val('');
} else {
newsletterAlert( msg );
}
},
error: function(msg) {
newsletterAlert('Error! ' + msg.statusText);
}
});
}
});
})();
Any help would be appreciated. Thanks
Don't use the same ID for the top and bottom forms.
An id must be unique in a document -- see MDN Docs.
Instead have two separate id's and reference them both in the one jQuery call when you are binding to the submit event:
$('#newsletter_top, #newsletter_bottom').on('submit', function(e) {
// ...
});
and in your HTML:
<form id="newsletter_top" ...>
</form>
<form id="newsletter_bottom" ...>
</form>

Validation message and focus dissapearing fast on jquery ajax script

I am trying to validate a form via jquery but after I hit the submit button the message appears, focus works, but only for 1 ms after message disappears and field looses focus.
Jquery Ajax
$(document).on('submit','.subscribe',function(e) {
var reg = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
var name = $("#sname").val();
var email = $("#semail").val();
if( name == "" ) {
$("#submess").html('Please enter your name in the required field to proceed.');
$("#sname").focus();
}
else if( email == "" ) {
$("#submess").html('Please enter your email address in the required email field to proceed. Thanks.');
$("#email").focus();
}
else if(reg.test(email) == false) {
$("#submess").html('Sorry, your email address is invalid. Please enter a valid email address to proceed. Thanks.');
$("#email").focus();
}
else
{
e.preventDefault(); // add here
e.stopPropagation(); // add here
$.ajax({ url: 'lib/common-functions.php',
data: {action: 'subscribe',
sname: $("#sname").val(),
semail: $("#semail").val()},
type: 'post',
success: function(output) {
$("#submess").html(output);
}
});
}
});
HTML
<form name="subscribe" class="subscribe">
<div id="submess"></div>
<label class="lablabel">Name:</label><input type="text" class="subscribe-field" id="sname" name="sname"></br>
<label class="lablabel">Email:</label><input type="text" class="subscribe-field" id="semail" name="semail">
<input type="submit" id="ssub" value="Subscribe">
</form>
Where am i mistaking.
Add
e.preventDefault();
After
$(document).on('submit','.subscribe',function(e) {
Your page is reloading, that's the problem.
i.e.
$(document).on('submit','.subscribe',function(e) {
e.preventDefault();
// some more stuff
}
Working fiddle

submitting a form via AJAX

I have a form that looks as following:
<form accept-charset="UTF-8" action="{{ path("fos_user_resetting_send_email") }}" method="post">
<div class="field">
<label for="username">Email:</label>
<input class="text" id="passwordEmail" name="username" required="required" size="30" type="text">
<div class="field-meta">Put in your email, and we send you instructions for changing your password.</div>
</div>
<div class="field">
<input id="submitPasswordRequest" class="full-width button" name="commit" tabindex="3" type="submit" value="Get Password">
</div>
<div class="field center">
Nevermind, I Remembered
</div>
I am trying to do the post via AJAX, so I did a simple test like this:
$("#submitPasswordRequest").click(function() {
var username = $('#passwordEmail').value();
console.log(username);
/*
$.ajax({
type: "POST",
url: "/resetting/send-email",
data: { username: username}, // serializes the form's elements.
success: function( data ) {
console.log(data); // show response from the php script.
}
});
*/
return false;
});
However it seems that the click function is not triggered and it goes to posting the form via the regular form action. What am I doing wrong here? I want to handle this via AJAX.
When you click upon the button, you simply submit the form to the back-end. To override this behavior you should override submit action on the form. Old style:
<form onsubmit="javascript: return false;">
New style:
$('form').submit(function() { return false; });
And on submit you want to perform an ajax query:
$('form').submit(function() {
$.ajax({ }); // here we perform ajax query
return false; // we don't want our form to be submitted
});
Use jQuery's preventDefault() method. Also, value() should be val().
$("#submitPasswordRequest").click(function (e) {
e.preventDefault();
var username = $('#passwordEmail').val();
...
});
Full code: http://jsfiddle.net/HXfwK/1/
You can also listen for the form's submit event:
$("form").submit(function (e) {
e.preventDefault();
var username = $('#passwordEmail').val();
...
});
Full code: http://jsfiddle.net/HXfwK/2/
jquery and ajax
$('form id goes here).submit(function(e){
e.preventDefault();
var assign_variable_name_to_field = $("#field_id").val();
...
if(assign_variable_name_to_field =="")
{
handle error here
}
(don't forget to handle errors also in the server side with php)
after everyting is good then here comes ajax
datastring = $("form_id").serialize();
$.ajax({
type:'post',
url:'url_of_your_php_file'
data: datastring,
datatype:'json',
...
success: function(msg){
if(msg.error==true)
{
show errors from server side without refreshing page
alert(msg.message)
//this will alert error message from php
}
else
{
show success message or redirect
alert(msg.message);
//this will alert success message from php
}
})
});
on php page
$variable = $_POST['field_name']; //don't use field_id if the field_id is different than field name
...
then use server side validation
if(!$variable)
{
$data['error']= true;
$data['message'] = "this field is required...blah";
echo json_encode($data);
}
else
{
after everything is good
do any crud or email sending
and then
$data['error'] = "false";
$data['message'] = "thank you ....blah";
echo json_encode($data);
}
You should use the form's submit handler instead of the click handler. Like this:
$("#formID").submit(function() {
// ajax stuff here...
return false;
});
And in the HTML, add the ID formID to your form element:
<form id="formID" accept-charset="UTF-8" action="{{ path("fos_user_resetting_send_email") }}" method="post">
You need to prevent the form from submitting and refreshing the page, and then run your AJAX code:
$('form').on('submit',function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "/resetting/send-email",
data: $('form').serialize(), // serializes the form's elements.
success: function( data ) {
console.log(data); // show response from the php script.
}
});
return false;
});

clear form values after submission ajax

I am using the following script for validate my contact form.
//submission scripts
$('.contactForm').submit( function(){
//statements to validate the form
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
var email = document.getElementById('e-mail');
if (!filter.test(email.value)) {
$('.email-missing').show();
} else {$('.email-missing').hide();}
if (document.cform.name.value == "") {
$('.name-missing').show();
} else {$('.name-missing').hide();}
if (document.cform.phone.value == "") {
$('.phone-missing').show();
}
else if(isNaN(document.cform.phone.value)){
$('.phone-missing').show();
}
else {$('.phone-missing').hide();}
if (document.cform.message.value == "") {
$('.message-missing').show();
} else {$('.message-missing').hide();}
if ((document.cform.name.value == "") || (!filter.test(email.value)) || (document.cform.message.value == "") || isNaN(document.cform.phone.value)){
return false;
}
if ((document.cform.name.value != "") && (filter.test(email.value)) && (document.cform.message.value != "")) {
//hide the form
//$('.contactForm').hide();
//show the loading bar
$('.loader').append($('.bar'));
$('.bar').css({display:'block'});
/*document.cform.name.value = '';
document.cform.e-mail.value = '';
document.cform.phone.value = '';
document.cform.message.value = '';*/
//send the ajax request
$.post('mail.php',{name:$('#name').val(),
email:$('#e-mail').val(),
phone:$('#phone').val(),
message:$('#message').val()},
//return the data
function(data){
//hide the graphic
$('.bar').css({display:'none'});
$('.loader').append(data);
});
//waits 2000, then closes the form and fades out
//setTimeout('$("#backgroundPopup").fadeOut("slow"); $("#contactForm").slideUp("slow")', 2000);
//stay on the page
return false;
}
});
This is my form
<form action="mail.php" class="contactForm" id="cform" name="cform" method="post">
<input id="name" type="text" value="" name="name" />
<br />
<span class="name-missing">Please enter your name</span>
<input id="e-mail" type="text" value="" name="email" />
<br />
<span class="email-missing">Please enter a valid e-mail</span>
<input id="phone" type="text" value="" name="phone" />
<br />
<span class="phone-missing">Please enter a valid phone number</span>
<textarea id="message" rows="" cols="" name="message"></textarea>
<br />
<span class="message-missing">Please enter message</span>
<input class="submit" type="submit" name="submit" value="Submit Form" />
</form>
I need to clear the form field values after submitting successfully. How can i do this?
$("#cform")[0].reset();
or in plain javascript:
document.getElementById("cform").reset();
You can do this inside your $.post calls success callback like this
$.post('mail.php',{name:$('#name').val(),
email:$('#e-mail').val(),
phone:$('#phone').val(),
message:$('#message').val()},
//return the data
function(data){
//hide the graphic
$('.bar').css({display:'none'});
$('.loader').append(data);
//clear fields
$('input[type="text"],textarea').val('');
});
use this:
$('form.contactForm input[type="text"],texatrea, select').val('');
or if you have a reference to the form with this:
$('input[type="text"],texatrea, select', this).val('');
:input === <input> + <select>s + <textarea>s
$('.contactForm').submit(function(){
var that = this;
//...more form stuff...
$.post('mail.php',{...params...},function(data){
//...more success stuff...
that.reset();
});
});
Simply
$('#cform')[0].reset();
it works: call this function after ajax success and send your form id as it's paramete. something like this:
This function clear all input fields value including button, submit, reset, hidden fields
function resetForm(formid) {
$('#' + formid + ' :input').each(function(){
$(this).val('').attr('checked',false).attr('selected',false);
});
}
* This function clears all input fields value except button, submit, reset, hidden fields
* */
function resetForm(formid) {
$(':input','#'+formid) .not(':button, :submit, :reset, :hidden') .val('')
.removeAttr('checked') .removeAttr('selected');
}
example:
<script>
(function($){
function processForm( e ){
$.ajax({
url: 'insert.php',
dataType: 'text',
type: 'post',
contentType: 'application/x-www-form-urlencoded',
data: $(this).serialize(),
success: function( data, textStatus, jQxhr ){
$('#alertt').fadeIn(2000);
$('#alertt').html( data );
$('#alertt').fadeOut(3000);
resetForm('userInf');
},
error: function( jqXhr, textStatus, errorThrown ){
console.log( errorThrown );
}
});
e.preventDefault();
}
$('#userInf').submit( processForm );
})(jQuery);
function resetForm(formid) {
$(':input','#'+formid) .not(':button, :submit, :reset, :hidden') .val('')
.removeAttr('checked') .removeAttr('selected');
}
</script>
$.post('mail.php',{name:$('#name').val(),
email:$('#e-mail').val(),
phone:$('#phone').val(),
message:$('#message').val()},
//return the data
function(data){
if(data==<when do you want to clear the form>){
$('#<form Id>').find(':input').each(function() {
switch(this.type) {
case 'password':
case 'select-multiple':
case 'select-one':
case 'text':
case 'textarea':
$(this).val('');
break;
case 'checkbox':
case 'radio':
this.checked = false;
}
});
}
});
http://www.electrictoolbox.com/jquery-clear-form/
Set id in form when you submitting form
<form action="" id="cform">
<input type="submit" name="">
</form>
set in jquery
document.getElementById("cform").reset();
$('#formid).reset();
or
document.getElementById('formid').reset();
Vanilla!
I know this post is quite old.
Since OP is using jquery ajax this code will be needed.
But for the ones looking for vanilla.
...
// Send the value
xhttp.send(params);
// Clear the input after submission
document.getElementById('cform').reset();
}
just use form tag alone, like this :
$.ajax({
type: "POST",
url: "/demo",
data: dataString,
success: function () {
$("form")[0].reset();
$("#test").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='images/check.png' />"
);
});
}
});
e.preventDefault();
});
Using ajax reset() method you can clear the form after submit
example from your script above:
const form = document.getElementById(cform).reset();
If you are using a form tag in your form. Then
$("#cform")[0].reset();
This code will work perfectly but in case you are not using any form tag then you can try to set an empty value to each input field Like this.
$('input[type="text"],textarea').val('');

Categories