Form validation in HTML5 doesn't work - javascript

Hi Could you please have a look at my HTML and function? The required field doesn't work. Any ideas why?
<form action='contact_form.php' method='post' class="contactForm">
<div class="formSecWrap">
<input type="text" class="formField" title="Name" id="name" name="name" value="" required/>
<input type="text" class="formField" title="Email" name="email" id="email" value="" required/>
<input type="text" class="formField" title="Phone" name="phone" id="phone" value="" required />
<input type="text" class="formField" title="Date & Time" name="date" id="date" value="" required/>
</div>
<div class="formSecWrap formSecWrap2">
<textarea class="textarea formField" title="Message" name="message" id="message"></textarea>
</div>
<input class="button" id="submit-form" type="submit" name="submit" value="Send Message" />
<div id="success">
</div>
</form>
And here is my function. I am not sure why it doesn't pick it up as a required fields.I have not created this form myself but was trying to work it out somehow.
Thank you
(function($){
$(document).ready(function() {
$('#submit-form').click(function(e){
e.preventDefault();
var reg = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
var name = $('#name').val(),
email = $('#email').val(),
phone = $('#phone').val(),
date = $('#date').val(),
message = $('#message').val(),
data_html,
success = $('#success');
if(name == "")
$('#name').val('Please enter your name.');
if(phone == "")
$('#phone').val('Please enter your phone number.');
if(date == "")
$('#date').val('Please enter a date and time.');
if(email == ""){
$('#email').val('Your email is required.');
}else if(reg.test(email) == false){
$('#email').val('Invalid Email Address.');
}
if(message == "")
$('#message').val('Message is required.');
if(message != "" && name != "" && reg.test(email) != false) {
data_html = "name=" + name + "&email="+ email + "&message=" + message + "&phone="+ phone + "&date="+ date;
//alert(data_html);
$.ajax({
type: 'POST',
url: '../contact_form.php',
data: data_html,
success: function(msg){
if (msg == 'sent'){
success.html('<div class="alert alert-success">Message <strong>successfully</strong> sent!</div>') ;
$('#name').val('');
$('#phone').val('');
$('#email').val('');
$('#date').val('');
$('#message').val('');
}else{
success.html('<div class="alert alert-error">Message <strong>not</strong> sent! Please Try Again!</div>') ;
}
}
});
}
return false;
});
});
});

try to pass arguments to you anonymous function
(function($){
//all that code
})(jQuery);

You can try executing the anonymous function something like:
(function($){
//Your code
}.call(this));
Please create the fiddle if the problem does not get resolved

anonymous function should be called for execution:
(function($){
//your code
})(jQuery);
for calling anonymous function use () right after the function ends, and pass jQuery parameter.

Remove the first and the last lines from your javascript.
(function($){
and
});
It wraps the code into an anonymous function which isn't invoked so you don't bind the click event to the submit button.

its working fine in both firefox and chrome..
Still if does not work you can check this out
HTML form required command not working?

Related

Ajax function not working on the form - jQuery

I have live validation for forms its working fine But AJAX functions are not working. whenever I click submit its directly redirected to the mailer.php without ajax function. I tried all the ways to fix but no luck. Someone please help me out.
When I click submit button if all the fields are validated it should go to AJAX form and submit.
$(function validateForm(){
$("#cname").validate({
expression: "if (VAL) return true; else return false;",
message: "Please enter the Name"
});
$("#cnumber").validate({
expression: "if (VAL.match(/^[0-9\.\-\/]+$/)) return true; else return false;",
message: "Please enter a valid Phone number"
});
$("#csubject").validate({
expression: "if (VAL) return true; else return false;",
message: "Please enter the Subject"
});
$("#cemail").validate({
expression: "if (VAL.match(/^[^\\W][a-zA-Z0-9\\_\\-\\.]+([a-zA-Z0-9\\_\\-\\.]+)*\\#[a-zA-Z0-9_]+(\\.[a-zA-Z0-9_]+)*\\.[a-zA-Z]{2,4}$/)) return true; else return false;",
message: "Please enter a valid Email ID"
});
$("#cmessage").validate({
expression: "if (VAL) return true; else return false;",
message: "Please enter the Message"
});
var form = $('#ajax-contact');
var formMessages = $('#form-messages');
$(form).validated(function(e){
$(formMessages).addClass('wait').text("please wait...");
e.preventDefault();
var formData = $(form).serialize();
var action = $(this).attr('action');
$.post(action, $(form).serialize(),
function(data) {
if (data.match('success') != null) $('#ajax-contact .form-group, #ajax-contact .theme-btn').slideUp('slow');
}
)
.done(function(response) {
// Make sure that the formMessages div has the 'success' class.
$(formMessages).removeClass('error');
$(formMessages).addClass('success');
// Set the message text.
$(formMessages).text(response);
// Clear the form.
$('#cname').val('');
$('#cemail').val('');
$('#cnumber').val('');
$('#csubject').val('');
$('#cmessage').val('');
gtag('event', 'form_submission', {
'event_category': 'contact_us',
'event_label': 'success'
});
})
.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
<form id="ajax-contact" method="post" action="mailer/function/smtpemail.php" class="wpcf7-form AdvancedForm" autocomplete="on">
<div class="form-group">
<input id="cname" type="text" name="cname" value="" placeholder="NAME">
</div>
<div class="form-group">
<input id="cemail" type="email" data-missing="This field is required" data-mismatch="Please include a valid email" name="cemail" value="" placeholder="EMAIL">
</div>
<div class="form-group">
<input id="cnumber" type="text" maxlength="15" name="cnumber" value="" placeholder="MOBILE">
</div>
<div class="form-group">
<input id="csubject" type="text" name="csubject" value="" placeholder="SUBJECT">
</div>
<div class="form-group">
<textarea id="cmessage" draggable="false" name="cmessage" placeholder="YOUR MESSAGE"></textarea>
</div>
<div class="form-group">
<button onclick='return validateForm()' type="submit" id="submit" class="theme-btn btn-style-four">Submit</button>
</div>
<div id="form-messages"></div>
</form>
You can use the submit function:
$("#ajax-contact").submit(function(e) {
if (!yourValidationFunction()) {
e.preventDefault();
}
});

HTML. How to check If user entered text in form?

So I have form with First_Name, Last_Name, City and Email. I need to check If fields are not empty.
For now, after clicking submit It redirecting to GetFbId.php from here I have 5 values to insert to database: FB_Id, First_Name, Last_Name, City and Email
Form.html
<!DOCTYPE html>
<html>
<head>
<title>Registracija</title>
<meta name="robots" content="noindex, nofollow">
<!-- include css file here-->
<link rel="stylesheet" href="css/style.css"/>
<!-- include JavaScript file here-->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript" src="js/registration.js"></script>
</head>
<body>
<div class="container">
<div class="main">
<form class="form" method="post" action="#">
<h2>Registracijos forma</h2><hr/>
<label>First Name: </label>
<input type="text" name="first_name" id="first_name" required>
<label>Last Name: </label>
<input type="text" name="last_name" id="last_name" required>
<label>City: </label>
<input type="text" name="city" id="city" required>
<label>Email: </label>
<input type="text" name="email" id="email" required>
<input type="submit" name="register" id="register" value="Register">
</form>
</div>
</div>
</body>
</html>
As you see for now It have action="GetFbId.php". I have JS script to check It, but It not working for me. JS is called: registration.js
I'm including in Form.html, inside <head> tags following:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript" src="js/registration.js"></script>
And instead of action="GetFbId.php"> I've tried to use action="#">, but in this case nothing happens after I click submit button.
registration.js* looks like:
$(document).ready(function(){
$("#register").click(function(){
var first_name = $("#first_name").val();
var last_name = $("#last_name").val();
var city = $("#city").val();
var email = $("#email").val();
if( first_name =='' || last_name =='' || email =='' || city =='')
{
alert("Fill all fields.");
}
else if((first_name.length)<3)
{
alert("Too short first name.");
}
else if((last_name.length)<4)
{
alert("Too short last name.");
}
else
{
$.post("GetFbId.php",{first_name: first_name, last_name: last_name, city: city, email: email},
function(data) {
if(data=='Success')
{
$("form")[0].reset();
}
alert(data);
});
}
});
});
And in GetFbId.php I'm trying to get variables in following:
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$city = $_POST['city'];
$email = $_POST['email'];
But no action (nothing happens) when submit button is clicked. Have you ideas how to fix It?
You need to prevent the default submit action. Otherwise, the button click submits the form, regardless of what you are doing in JavaScript. Your script both validates the input and uses jQuery's .post(), so you need to prevent that default submit action with:
event.preventDefault();
I would also recommend returning false when validation fails.
Updated JavaScript:
$(document).ready(function () {
$("#register").click(function () {
event.preventDefault(); // <-- ADDED THIS LINE
var first_name = $("#first_name").val();
var last_name = $("#last_name").val();
var city = $("#city").val();
var email = $("#email").val();
if (first_name == '' || last_name == '' || email == '' || city == '') {
alert("Fill all fields.");
return false; // <-- ADDED THIS LINE
} else if ((first_name.length) < 3) {
alert("Too short first name.");
return false; // <-- ADDED THIS LINE
} else if ((last_name.length) < 4) {
alert("Too short last name.");
return false; // <-- ADDED THIS LINE
} else {
$.post("GetFbId.php", {
first_name: first_name,
last_name: last_name,
city: city,
email: email
},
function (data) {
if (data == 'Success') {
$("form")[0].reset();
}
alert(data);
});
}
});
});
See demo: http://jsfiddle.net/BenjaminRay/n6jqvrra/
You can also let the browser handle the required field validation for you by adding "required" to the required fields. Then you only have to handle the $.post() side of things. However, this is not supported by all old browsers (e.g. IE8) so it's not guaranteed to stop the form from being submitted with empty values.
E.g.:
<input type="text" name="first_name" id="first_name" required>
And, of course, you will need to validate the input on the server side (PHP) as well.
Add an ID to your form:
<form class="form" id="form_id" method="post" action="GetFbId.php">
Now, instead of capturing the click event on #register, try to capture the submit event of the form.
$('#form_id').submit(function(evt) { // Better to use a form id
// First, avoid the form being submitted normally (forms change the website from which they are submitted)
evt.preventDefault();
// Now do your form checking...
});
So your code will look like:
HTML
<form class="form" method="post" action="GetFbId.php" id="form_id">
<h2>Registration</h2><hr/>
<label>First Name: </label>
<input type="text" name="first_name" id="first_name">
<label>Last Name: </label>
<input type="text" name="last_name" id="last_name">
<label>City: </label>
<input type="text" name="city" id="city">
<label>Email: </label>
<input type="text" name="email" id="email">
<input type="submit" name="register" id="register" value="Register">
</form>
Registration.js
$(document).ready(function(){
$("#form_id").submit(function(){ // Note the "submit" event OF THE FORM
var $form = $(this); // Save the context of the form
event.preventDefault(); // Prevent the form from being submitted normally
var first_name = $( '#first_name' ).val();
var last_name = $( '#last_name' ).val();
var city = $( '#city' ).val();
var email = $( '#email' ).val();
if (
first_name.length == 0
||
last_name.length == 0
||
email.length == 0
||
city.length == 0
)
{
alert('All fields are required.');
}
else if ( first_name.length < 3 ) alert('First name is too short');
else if ( last_name.length < 4 ) alert('Last name is too short');
else
{
$.post( "GetFbId.php", $form.serialize() )
.done(function(data) {
alert(data); // Print what the server returns
})
.fail(function() {
alert('An error has occured');
})
;
}
});
});

Validate form, check if user exists, register them. All with Ajax

My javascript is inside an html file called register.html.
The user submits the form. This should then trigger the $('input[name="createacc"]').click(function (e) AJAX then sends those 4 variables to checkuser.php. Checkuser.php should then check to see if the username exists. If it does exist, it should echo 0. If it does not exists, it should echo 1. Register.html then checks to see what checkuser.php echoed. If the echo was "0" then, then an alert box should appear saying username unavailable. If the echo was "1" or anything else, register.html should run $("#registerform").submit(); which then does the php script. This should all happen without leaving the register.html page.
I check chrome's built in debugger and I see that if the account exists checkuser.php writes back 0 and if the account doesn't it writes back 1. But for some reason nothing else happens. The account does not register nor do I get an alert box saying the username is unavailable
here is my register.html
<form ata-parsley-validate name="registerform" id="registerform" action="register.php" method="post">
<p>
<label for="firstname">First Name:</label>
<input name="firstname" id="firstname" maxlength="32" type="text" placeholder="Optional" />
</p>
<p>
<label for="username" id="usernameText">Username:</label>
<input data-parsley-pattern="^[A-Za-z0-9_]{3,15}$" data-parsley-length="[3, 15]" name="username" id="username" maxlength="32" type="text" data-parsley-error-message="Username needs to be between 3 and 15 characters. Case sensitive. No special characters allowed." required/>
</p>
<p>
<label for="password1">Password:</label>
<input name="password1" id="password1" data-parsley-pattern="^[A-Za-z0-9_-]{5,25}$" data-parsley-length="[5, 25]" type="password" data-parsley-equalto="#password2" data-parsley-error-message="Passwords must match. Needs to be between 5 and 25 characters. Case sensitive. No special characters allowed." required/>
</p>
<p>
<label for="password2">Confirm Your Password:</label>
<input name="password2" id="password2" data-parsley-length="[5, 25]" data-parsley-error-message="Passwords must match. Needs to be between 5 and 25 characters. Case sensitive. No special characters allowed." data-parsley-pattern="^[A-Za-z0-9_-]{5,25}$" type="password" data-parsley-equalto="#password1" required/>
</p>
<p>
<label for="email">E-Mail:</label>
<input data-parsley-trigger="change" name="email" id="email" maxlength="1024" type="email" required/>
</p>
<p>
<input type="submit" id="submit" class="submit" name="createacc" value="Register" />
</p>
</form>
Here is my javascript
<script>
$(document).ready(function () {
$('input[name="createacc"]').click(function (e) {
var username = $('input[name="username"]').val();
var firstname = $('input[name="firstname"]').val();
var password1 = $('input[name="password1"]').val();
var email = $('input[name="email"]').val();
e.preventDefault();
$.ajax({
type: 'POST',
data: {
username: username,
firstname: firstname,
password1: password1,
email: email
},
url: 'checkuser.php',
success: function (data) { //Receives the data from the php code
if (data === "0") {
alert("Username Unavailable");
} else {
$("#registerform").submit();
alert("Account successfuly created");
}
},
error: function (xhr, err) {
console.log("readyState: " + xhr.readyState + "\nstatus: " + xhr.status);
console.log("responseText: " + xhr.responseText);
}
});
});
});
</script>
Update - I have fixed parts of my code through the help of others below me. My only issue now is that $("#registerform").submit(); doesn't do anything
You are trying to return and JSON not setting
header('Content-type: application/json');
Decide whether you want to pass plaintext or json. Your string might be now "0", not 0
Try
if (data === '"0"') {
I think the problem is in your success.you have written If it does exist, it should echo 0. If it does not exists, it should echo 1.you should use:
success: function (data) { //Receives the data from the php code
if (data == '"0"') { //register if user exists.
$("#registerform").submit();
} else {
alert("Username Unavailable");
}

JS/jQuery event.submit/return true not woking

I am wondering if someone can help me as i cant figure this out. I have this validation script that checks an email form for contents and valid email and it is working correctly however it is not submitting the form if everything is okay..it just removes to error messages and does nothing.
I have a strange feeling it will be something stupid but i cant see anything wrong here.
HTML
<!DOCTYPE html>
<html>
<head>
<?php include('includes/head.php'); ?>
<script type="text/javascript" src="js/contactVal.js"></script>
</head>
<body>
<?php include('includes/navbar.php'); ?>
<div class="container">
<div class="row">
<div class="col-md-8">
<h3>Contact Form</h3>
<p>Use this handy little contact form to get in contact with me about anything at all. If you have a job offer or any questions about me then feel free to drop me a message, ill get back to you as soon as possible.</p>
<hr>
<div id="form-response">
</div>
<form id="mailer" action="scripts/mailer.php" method="POST">
<h3>Name:</h3>
<input type="text" id="name" name="name" placeholder="Enter your name"></input><br />
<h3>Email:</h3>
<input type="email" id="email" name="email" placeholder="Enter your email address"></input><br />
<h3>Subject:</h3>
<input type="text" id="subject" name="subject" placeholder="Enter the subject of your message"></input><br />
<h3>Message:</h3>
<textarea id="message" name="message" placeholder="Enter your message here..."></textarea><br />
<input type="submit" name="submit" id="submit" value="Send"></input><br /><br />
<input type="hidden" name="honeypot" id="honeypot" value="http://" />
<input type="hidden" name="human" id="human" value="" />
</form>
</div>
<div class="col-md-4">
<h3>Details</h3>
<p><img class="about-arrow" src="img/icons/arrow.png" />Email: contact#alexvolley.co.uk</p>
<p><img class="about-arrow" src="img/icons/arrow.png" />Website: www.alexvolley.co.uk</p>
<p><img class="about-arrow" src="img/icons/arrow.png" />Mobile: On request</p>
<hr>
<h3>Socials</h3>
<a class="big" href="http://www.facebook.com/oukp3ngu1nx"><img class="about-arrow" src="img/icons/arrow.png" />Facebook</a><br />
<a class="big" href="http://www.twitter.com/alex_volley_"><img class="about-arrow" src="img/icons/arrow.png" />Twitter</a><br />
<a class="big" href="https://www.linkedin.com/pub/alex-volley/97/27/906"><img class="about-arrow" src="img/icons/arrow.png" />LinkedIn</a><br />
</div>
</div>
</div>
<?php include('includes/footer.php'); ?>
</body>
</html>
JAVASCRIPT
$(document).ready(function(){
$('#form-response').hide();
$('#form-response').click(function(){
$('#form-response').fadeOut();
});
$('#submit').click(function(){
event.preventDefault();
var valid = '';
var name = $('form #name').val();
var email = $('form #email').val();
var subject = $('form #subject').val();
var message = $('form #message').val();
var honey = $('form #honeypot').val();
var human = $('form #human').val();
var filter = /^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
//check for human interaction
if(honey == 'http://' && human == ""){
//check fields
if(name == '' || null || name.length < 2){
valid = '<p>You need to enter your name.</p>';
}
if(email == '' || null || email.length < 5){
valid += '<p>You need to enter an email address.</p>';
}
if(!email.match(filter)){
valid += '<p>You need to enter a valid email address.</p>';
}
if(subject == '' || null || subject.length < 2){
valid += '<p>You need to enter a valid subject.</p>';
}
if(message == '' || null || message.length < 30){
valid += '<p>You need to enter a message of at least 30 characters.</p>';
}
//check if valid
if(valid != ''){
$('#form-response').removeClass().addClass('error').html('<h3>There was a few problems..</h3>' + valid).fadeIn('slow');
} else {
$('#form-response').fadeOut('slow');
$('#form-response').hide();
return true;
}
} else {
//spambot
error = '<p>Back of bot boy.</p>';
}
});
});
You did not pass event in the function arguments:
$('#submit').click(function( event ){
event.preventDefault();
You're probably better off using the submit event and letting the submit button do it's job:
$('#mailer').submit(function( event ){
event.preventDefault();
........
if(valid != ''){
$('#form-response').removeClass().addClass('error').html('<h3>There was a few problems..</h3>' + valid).fadeIn('slow');
this.submit(); //ONCE EVERYTHING CHECKS OUT
} else {
.....
JS FIDDLE DEMO
EDIT
To resolve the error Uncaught TypeError: object is not a function, please change the name of your submit button to something else: this.submit -- the button, is conflicting with this.submit() -- the function.
Here is a version that works fine after changing: name="submit" to name="submit-button"
By the way your input elements do not need a closing tag </input>
REF: Uncaught TypeError: object is not a function, button inside form
May be you can try following code. On Submit button click validate form and if everything is fine submit form using .submit method.
$('#submit').click(function( event ){
event.preventDefault();
............
if(valid != ''){
$('#form-response').removeClass().addClass('error').html('<h3>There was a few problems..</h3>' + valid).fadeIn('slow');
} else {
$('#form-response').fadeOut('slow');
$('#form-response').hide();
$('#mailer').submit(); //ONCE EVERYTHING CHECKS OUT
}
..............

Why does this form submit on click of the submit button

<script type="text/javascript">
var geid = function(x) {
var element = document.getElementById(x);
return element;
}
function submitForm(){
var password = geid('password').value;
var passwordConfirm = geid('passwordConfirm');
//THIS IS OF HIGH IMPORTANCE THAT THIS CONFIRM PASSWORD MATCHES
//WILL NEED TO VALIDATE IT IN THE PHP AS WELL>
else if (password == ""){
registerMessage.innerHTML = "Please enter your Password.";
return false;
}
else if (passwordConfirm == "") {
registerMessage.innerHTML = "Please confirm your password.";
return false;
}
else if (passwordConfirm != password) {
registerMessage.innerHTML = "Your passwords don't match.";
return false;
}
else {
registerMessage.innerHTML = "Taking you to your profile, please wait a moment...";
document.forms['registerform'].submit();
}
}
<form method="post" action="register.php" id="registerform" onsubmit="return submitForm()">
<label for="password" class="registerLabel">Password</label>
<input type="password" name="password" id="password" class="registerText" /> <br />
<label for="passwordConfirm" class="registerLabel">Confirm Password</label>
<input type="password" name="passwordConfirm" id="passwordConfirm" class="registerText" /> <br />
<div class="submitMessage">
<input type="submit" id="submit" name="submit" value="Register" class="registerButton cleangray" /><br />
<div id="registerMessage"><?php echo $error ?></div>
</div>
<div class="clear"></div>
</form>
You can't start with else if; you need to start with if
if (password == ""){
registerMessage.innerHTML = "Please enter your Password.";
return false;
}
That's preventing any of your validation code from running and just submitting the form using the standard submit mechanism.
This also isn't the best way to approach the validation. Rather than return at each error, you could build up a string of messages and report them all back in one go. That way the user knows everything that's wrong — your current method will only ever set one message.
Because you have error in JavaScript, you are using else if without defining if first. Because of this error all JavaScript code fail.
Change
else if (password == ""){
to
if (password == ""){
Working demo http://jsfiddle.net/Zs3km/
BTW in your code HTML is within <script> tag, not sure if its your mistake just here. You have to close <script> tag before <form> tag is opened.

Categories

Resources