I am trying to implement the simple form validation plugin found here: http://www.jquery4u.com/forms/basic-jquery-form-validation-tutorial/
but I cannot seem to get it working.
I have a simple form:
<form id="signupform" name="signupform" action="page" method="post" novalidate="novalidate">
<input type="text" id="signupusername" name="signupusername">
<input type="text" id="signupemail" name="signupemail">
<input type="password" id="signuppassword" name="signuppassword">
<input type="text" id="signupfirstname" name="signupfirstname">
<input type="text" id="signuplastname" name="signuplastname">
<input type="checkbox" name="tandc" value="tandcyes"> I agree
<button type="submit" value="Signup" class="submit">Signup</button>
</form>
And the associated plugin script:
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.min.js"></script>
<script type="text/javascript">
(function($,W,D)
{
var JQUERY4U = {};
JQUERY4U.UTIL =
{
setupFormValidation: function()
{
//form validation rules
$("#signupform").validate({
rules: {
signupusername: "required",
signupfirstname: "required",
signuplastname: "required",
signupemail: {
required: true,
email: true
},
signuppassword: {
required: true,
minlength: 5
},
tandcyes: "required"
},
messages: {
signupusername: "Please enter your User Name",
signupfirstname: "Please enter your firstname",
signuplastname: "Please enter your lastname",
signuppassword: {
required: "Please provide a password",
minlength: "Your password must be at least 5 characters long"
},
signupemail: "Please enter a valid email address",
tandcyes: "Please accept our policy"
},
submitHandler: function(form) {
form.submit();
}
});
}
}
//when the dom has loaded setup form validation rules
$(D).ready(function($) {
JQUERY4U.UTIL.setupFormValidation();
});
})(jQuery, window, document);
But it will just not work.
Of course I have checked both the plugin and link to JQuery are present and correct. Nothing appears in the console either. It just doesnt seem to trigger.
Does anyone know whats going on?
Thanks!
The problem is that you have included 2 times the same script.
The functions in script with validation appear 2 times in the source. Which is rather hard for the browser to know which one to pick.
Check head for two scripts.
Please add all your inputs in the form they are not present in the form tags.
<form>
<input type=... />
<input type=... />
</form>
if you close the form before your inputs that is the problem.
use this page and its works
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.min.js"></script>
<title>Basic jQuery Validation Form Demo | jQuery4u</title>
<link rel="stylesheet" type="text/css" href="bootstrap.css">
<script type="text/javascript">
(function($,W,D)
{
var JQUERY4U = {};
JQUERY4U.UTIL =
{
setupFormValidation: function()
{
//form validation rules
$("#signupform").validate({
rules: {
signupusername: "required",
signupfirstname: "required",
signuplastname: "required",
signupemail: {
required: true,
email: true
},
signuppassword: {
required: true,
minlength: 5
},
tandcyes: "required"
},
messages: {
signupusername: "Please enter your User Name",
signupfirstname: "Please enter your firstname",
signuplastname: "Please enter your lastname",
signuppassword: {
required: "Please provide a password",
minlength: "Your password must be at least 5 characters long"
},
signupemail: "Please enter a valid email address",
tandcyes: "Please accept our policy"
},
submitHandler: function(form) {
form.submit();
}
});
}
}
//when the dom has loaded setup form validation rules
$(D).ready(function($) {
JQUERY4U.UTIL.setupFormValidation();
});
})(jQuery, window, document);
</script>
</head>
<body>
<h1>Basic jQuery Validation Form Demo</h1>
<!-- HTML form for validation demo -->
<form id="signupform" name="signupform" action="page" method="post" novalidate="novalidate">
<input type="text" id="signupusername" name="signupusername">
<input type="text" id="signupemail" name="signupemail">
<input type="password" id="signuppassword" name="signuppassword">
<input type="text" id="signupfirstname" name="signupfirstname">
<input type="text" id="signuplastname" name="signuplastname">
<input type="checkbox" name="tandc" value="tandcyes"> I agree
<button type="submit" value="Signup" class="submit">Signup</button>
</form>
<!-- END HTML form for validation -->
</body>
</html>
Related
I have a form I am trying to validate using JQuery Validate, which works fine. When the submit button is clicked, the submitHandler should 1. disable the button (to prevent multiple submissions) and 2. change the button text.
As is, the code works for validation but does not invoke the submitHandler.
I've looked over many threads on here, saying that the button must be type="submit", inside the <form> tags, etc. and cannot figure this out. The button is still able to be clicked multiple times.
Any help?
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jQuery.Validate/1.6/jQuery.Validate.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#freebottleform").validate({
rules: {
address : {
required: true
},
city : {
required: true
},
state : {
required: true
},
zipcode : {
required: true
},
phoneNumber : {
required: true,
phoneUS: true
},
},
//Specify the validation error messages here
messages: {
email: {
required: "Please enter email address",
email: "Please enter a valid email address"
},
phoneNumber: {
required : "Please enter your mobile number",
digits: "Please enter digits only"
}
},
submitHandler: function (form) {
$("#finalSubmit").attr("disabled", true);
$("#finalSubmit").html("Submitting... please wait.");
form.submit();
}
});
});
</script>
<!DOCTYPE html>
<html lang="en">
<div class="freebottleform">
<form method="post" id="freebottleform" name="freebottleform" action="p6.php">
Please enter your shipping details.<br>
<br>
Address:<br>
<input type="text" name="address" class="required" placeholder="Please enter your address."/><br>
<input type="text" name="address2" placeholder="Suite/Apt/Etc."/><br>
<br>
City:<br>
<input type="text" name="city" class="required" placeholder="Please enter your city."/><br>
<br>
State:<br>
<input type="text" name="state" class="required" placeholder="Please enter your state."/><br>
<br>
Zip Code:<br>
<input type="text" name="zipcode" class="required" placeholder="Please enter your zipcode."/><br>
<br>
Phone Number:<br>
<input type="text" name="phoneNumber" class="required" placeholder="Please enter your phone number."/><br>
<br>
<label><input type="checkbox" name="subscribe" id="subscribe" value="true" checked/> Subscribe to our newsletter to get FREE weekly tips sent right to your inbox!</label><br>
<br>
<button id="finalSubmit" type="submit" name="submit" value="final" >CONTINUE</button>
</form>
</div>
</html>
You can do your validation and disable the button on click event of button, at client side.
<script type="text/javascript">
$("#finalSubmit").click(function()
{
//do your validation and if correct then disable the button
$("#finalSubmit").attr("disabled", true);
//other work if any
}
);
</script>
1st of all instead of making validations with jQuery, make validations on server side like with PHP etc., and reflect the output on the display page.
An example here:
index.php
<!DOCTYPE html>
<html>
<head>
<title>Site Title</title>
</head>
<body>
<h1>Form</h1>
<div class="message"></div>
<form method="post" action="" name="registrationForm">
First Name <input type="text" name="fname"><br>
Last Name <input type="text" name="lname"><br>
Phone <input type="text" name="phone"><br>
<input type="submit" value="Register" class="regbtn">
</form>
<script type="text/javascript" src="js/jquery.js"></script>
<script>
$(document).ready(function(){
$(".regbtn").click(function(){
var form = document.registrationForm;
var dataString = $(form).serialize();
$.ajax({
type: 'POST',
url: "your-processing-page.php",
data: dataString,
cache: true,
beforeSend: function(){
$('.message').hide();
$(".regbtn").prop('disabled', true).val('Please wait...');
},
success: function(data){
$('.message').html(data).fadeIn();
$(".regbtn").prop('disabled', false).val('Register');
}
});
return false;
});
});
</script>
</body>
</html>
your-processing-page.php
<?php
$fname = (!empty($_POST['fname']))?$_POST['fname']:null;
$lname = (!empty($_POST['lname']))?$_POST['lname']:null;
$phone = (!empty($_POST['phone']))?$_POST['phone']:null;
if($_POST){
// Perform Checks Here
if(trim($fname) == ''){
echo "Please enter first name.";
}else if(trim($lname) == ''){
echo "Please enter last name.";
}else if((strlen($phone)) == 0){
echo "Please enter a phone number";
}else if((strlen($phone)) < 10){
echo "Phone number must not contain less than 10 digits.";
}else if((strlen($phone)) > 10){
echo "Phone number must not contain more than 10 digits.";
}else{
// If all checks are cleared perform your query
$stmt = $pdo->prepare("INSERT INTO members(mem_fname, mem_lname, mem_phone)VALUS(:fname, :lname, :phone)");
$stmt-> bindValue(':fname', $fname);
$stmt-> bindValue(':lname', $lname);
$stmt-> bindValue(':phone', $phone);
$stmt-> execute();
if($stmt){
echo "Success! User has been registered.";
}else{
echo "Sorry, something went wrong. Please refresh the page and try again!";
}
}
}
?>
That's a complete answer. Here:
Validation is done on server side using PHP (better method and must be followed).
jQuery disables submit button to prevent double submission after click.
jQuery changes button text value when submit button is pressed and changes back to default on successful return from form submission.
Note: The above is a fully working "standard" coding sample. That's how you should code. However, perform other necessary checks as per your need. Take the above coding only as a sample to frame your own code. Happy coding :)
Change the submit button name to something else because it overrides the submit() function on the form, then this code should work for you(Reference). ↓↓
$(document).ready(function() {
$("#freebottleform").validate({
rules: {
address: {
required: true
},
city: {
required: true
},
state: {
required: true
},
zipcode: {
required: true
},
phoneNumber: {
required: true,
// phoneUS: true,
digits: true
},
},
//Specify the validation error messages here
messages: {
email: {
required: "Please enter email address",
email: "Please enter a valid email address"
},
phoneNumber: {
required: "Please enter your mobile number",
digits: "Please enter digits only"
}
},
submitHandler: function(form) {
$("#finalSubmit").attr("disabled", true);
$("#finalSubmit").html("Submitting... please wait.");
setTimeout(function() {
form.submit();
}, 3000);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.1/jquery.validate.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<div class="freebottleform">
<form method="post" id="freebottleform" name="freebottleform" action="p6.php">
Please enter your shipping details.<br>
<br> Address:
<br>
<input type="text" name="address" class="required" placeholder="Please enter your address." /><br>
<input type="text" name="address2" placeholder="Suite/Apt/Etc." /><br>
<br> City:
<br>
<input type="text" name="city" class="required" placeholder="Please enter your city." /><br>
<br> State:
<br>
<input type="text" name="state" class="required" placeholder="Please enter your state." /><br>
<br> Zip Code:<br>
<input type="text" name="zipcode" class="required" placeholder="Please enter your zipcode." /><br>
<br> Phone Number:<br>
<input type="text" name="phoneNumber" class="required" placeholder="Please enter your phone number." /><br>
<br>
<label><input type="checkbox" name="subscribe" id="subscribe" value="true" checked/> Subscribe to our newsletter to get FREE weekly tips sent right to your inbox!</label><br>
<br>
<button id="finalSubmit" type="submit" name="save" value="final">CONTINUE</button>
</form>
</div>
</html>
I am developing a web directory with a form on one of its pages. JS validation plug in is used. While submitting the form without filling any Input fields, the form throws errors below each input field as expected! But submitting the form with just one input box filled in refreshes the current page as the action value is set to current page with PHP codes in it, instead of staying on the same page to continue to throw errors for the rest of the fields that are yet to be filled in! I have searched online to find nothing useful in figuring out what is wrong with the script. Could anyone here please look into the code below and recommend the best solution? Thanks.
$(document).ready(function() {
$("#userForm").validate({
rules: {
cname: {
required: true,
lettersonly: true,
minlength: 3
},
cemail: {
required: true,
email: true
},
cphone: {
required: true,
number: true,
minlength: 10,
maxlength: 10
},
cbusiness: {
required: true,
url: true
},
cbcategory: {
required: true,
minlength: 6
},
curl: {
required: true,
minlength: 6
},
},
messages: {
cname: "Please enter your name",
cemail: "Please enter a valid email address",
cphone: {
required: "Please enter your phone number",
number: "Please enter only numeric value"
},
cbusiness: {
required: "Please enter your business",
},
cbcategory: {
required: "Please enter a business category",
},
curl: {
required: "Please enter the URL to your website",
},
}
});
});
The form is as below.
<form action="" method="post" name="userForm" id="userForm">
<input type="text" name="cname" id="cname" placeholder=" Your Name">
<input type="text" name="cemail" id="cemail" class="email" placeholder="Your Email">
<input type="text" name="cphone" id="cphone" placeholder="Your Phone">
<input type="text" name="cbusiness" id="cbusiness" class="email" placeholder=" Your Business">
<input type="text" name="cbcategory" id="cbcategory" placeholder="Business category">
<input type="text" name="curl" id="curl" class="email" placeholder="URL"><br>
<label for='message'>Enter the code in the box below : </label>
<img src="captcha.php?rand=<?php echo rand();?>" id='captchaimg'>
<input type="text" id="captcha_code" name="captcha_code">
<input type="submit" name="Submit" id="Submit" value="Submit" class="button1"><br>
Can't read the image? click <a href='javascript: refreshCaptcha();'>here</a> to refresh.
</form>
Assuming you have included the validation libraries corectly, you will have to set messages for all of the validation types like:
messages: {
cname: {
required: "Please enter your name",
lettersonly: "Letters only",
minlength: "Min length 3 required"
},
cemail: {
required: "Please enter a valid email address",
email: "Invalid email"
}
}
Working JSFIDDLE.
You have to include the plugin files something like this:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.16.0/additional-methods.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.16.0/jquery.validate.js"></script>
UPDATE:
After discussing with OP on chat, we came to the conclusion that the plugin files had to be included correctly and there was an incompatibility between the jQuery version(v 1.7.1) he used and the plugin version(v 1.16.0). So we had to add a custom method for lettersonly.
The code for custom method:
jQuery.validator.addMethod("lettersonly", function(value, element) {
return this.optional(element) || /^[a-z]+$/i.test(value);
}, "Letters only please");
I'm using jquery validation plugin to validate a form. It is working if all fields are left blank. But if I entered a file in the input field and leave blank the other required fields it doesn't validate the other elements anymore it just submit the form to the server.
<script>
$().ready(function() {
$("#form1").validate({
submitHandler: function (form) {
$.ajax({
type: $(form).attr('method'),
url: $(form).attr('action'),
data: $(form).serialize(),
})
.done(function (response) {
jAlert(response);
});
return false;
},
ignore: [],
rules: {
title: { required: true, minlength: 2, maxlength: 25 },
text1: {
required: function() {
CKEDITOR.instances.text1.updateElement();
}
},
text2: {
required: function() {
CKEDITOR.instances.text2.updateElement();
}
},
newsimage: {
required: true,
accept: "image/*"
},
},
messages: {
title: {
required: "Please enter the Title",
minlength: "Title must consist of at least 2 characters"
},
text1: {
required: "Please enter text",
minlength: "Must consist of at least 2 characters"
},
text2: {
required: "Please enter text",
minlength: "Must consist of at least 2 characters"
}
}
});
});
</script>
Here's the form
<form id="Form1" enctype="multipart/form-data" method="post" action="save.php" >
Title: <input name="title" size="40" maxlength="255">
<br>
<label for="newsimage">News Image</label>
<input type="file" id="newsimage" name="newsimage">
<br> News Summary:
<textarea id="text1" name="text1" rows="7" cols="30"></textarea>
<script type="text/javascript">
CKEDITOR.replace( 'text1' );
</script>
<br> News Full Story:
<textarea id="text2" name="text2" rows="7" cols="30"></textarea>
<script type="text/javascript">
CKEDITOR.replace( 'text2' );
</script>
<br> <input type="submit" name="submit" value="Add News">
You could use required on your form tags like this :
<input name="title" size="40" maxlength="255" required>
that should force some input. ( it is not sanitized )
It wasn't working on my end because I was missing additional-methods.js, so adding it solve the problem.
<script src="js/additional-methods.min.js"></script>
Try this user friendly validation plugin
https://github.com/vanarajcs/jquery-form-validation
in order to activate any jquery validation library first of all you need to define that library below jquery cdn. your structure should be like this:
<!-- define jquery file -->
<!-- Now define jquery validation library -->
for a safer side define you jquery file on header and your validation library after main code.
Hello guys I'm doing a login form with jquery validation which checks if the user id and password are valid.
This is what I've tried so far:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.8/jquery.validate.min.js"></script>
<script language="javascript">
$(document).ready(function(){
$("#loginForm").validate({
rules: {
username: "required",
password: {
required: true
}
},
messages: {
username: "This field is required",
password: {
required: "This field is required"
}
}
});
$("#loginForm").submit(function(){
$("#report").removeClass().addClass('loader').html('<img src="img/login/spinner.gif">').fadeIn(1000);
$.post("checklogin.php",{ username:$('#username').val(),password:$('#password').val()},function(data){
if(data=='yes'){
$("#report").fadeTo(200,1,function(){
$(this).html('<img src="img/login/spinner.gif">').addClass('log').fadeTo(900,1,function(){
document.location='processed.php';
});
});
}
else {
$("#report").fadeTo(200,1,function(){
$(this).html('<img src="img/login/icon_error.gif"> Username or password error.').addClass('error').fadeTo(900,1);
});
}
});
return false;
});
$("#password").blur(function(){
$("#login_form").trigger('submit');
});
});
</script>
What I want to happen is, if fields have empty values then it should validate and display fields are required. But my form displays the error message and goes to check as if the fields have values. Why is that happening? Any ideas to resolve this issue? Thanks.
UPDATE: index.html
<form class="form-signin" action="checklogin.php" method="post" id="loginForm">
<img alt="" src="img/irasa_logoa.png" title="IRASA">
<h2 class="form-signin-heading">Log In</h2>
<input type="text" class="input-block-level" placeholder="User ID" name="username" id="username" class="required">
<input type="password" class="input-block-level" placeholder="Password" name="password" id="password" class="required">
<button class="btn btn-large btn-custom" type="submit">Log in</button>
<div id="report"></div>
</form>
</div> <!-- /container -->
Try this
$("#loginForm").validate({
rules: {
username: "required",
password: "required"
},
messages: {
username: "This field is required",
password: "This field is required"
},
submitHandler: function(form) {
$("#report").removeClass().addClass('loader').html('<img src="img/login/spinner.gif">').fadeIn(1000);
$.post("checklogin.php",{ username:$('#username').val(),password:$('#password').val()},function(data){
if(data=='yes'){
$("#report").fadeTo(200,1,function(){
$(this).html('<img src="img/login/spinner.gif">').addClass('log').fadeTo(900,1,function(){
document.location='processed.php';
});
});
} else {
$("#report").fadeTo(200,1,function(){
$(this).html('<img src="img/login/icon_error.gif"> Username or password error.').addClass('error').fadeTo(900,1);
});
}
});
return false;
})
});
$("#password").blur(function(){
$("#login_form").trigger('submit');
});
}
});
I think it is as simple as adding a "required" class in your input type. just add class="required".
This will work as you're using jquery.validate.min.js.
Refer: http://help.campaignmonitor.com/topic.aspx?t=194
If you are using jQuery validate then you should not also bind to the submit event for the form yourself. Put that code in a submitHandler instead. See http://jqueryvalidation.org/validate#submithandler
Edit to add example.
Note that I have not checked that your function (which you had as a submit event) is right - just copied it. I have also removed the rules since as #Sambhav Sharma said, you should simply add a "required" class to the fields and it is automatically required). I also assume the submit on blur should be triggered always, not after the validation submit. I have not tested any of this :)
$(document).ready(function(){
$("#loginForm").validate({
messages: {
username: "This field is required",
password: {
required: "This field is required"
}
},
submitHandler: function(){
$("#report").removeClass().addClass('loader').html('<img src="img/login/spinner.gif">').fadeIn(1000);
$.post("checklogin.php",{ username:$('#username').val(),password:$('#password').val()},function(data){
if(data=='yes'){
$("#report").fadeTo(200,1,function(){
$(this).html('<img src="img/login/spinner.gif">').addClass('log').fadeTo(900,1,function(){
document.location='processed.php';
});
});
} else {
$("#report").fadeTo(200,1,function(){
$(this).html('<img src="img/login/icon_error.gif"> Username or password error.').addClass('error').fadeTo(900,1);
});
}
});
return false;
})
});
$("#password").blur(function(){
$("#login_form").trigger('submit');
});
});
<script src="jquery.js"></script>
<script src="jquery.validate.js"></script>
<script>
$.validator.setDefaults({
submitHandler: function() {
alert("submitted!");
}
});
$().ready(function() {
// validate signup form on keyup and submit
$("#signupForm").validate({
rules: {
firstname: "required",
lastname: "required",
},
messages: {
firstname: "Please enter your firstname",
lastname: "Please enter your lastname",
username: {
required: "Please enter a username",
minlength: "Your username must consist of at least 2 characters"
},
}
});
});
</script>
</head>
<body>
<form class="cmxform" id="signupForm" method="get" action="">
<fieldset>
<legend>Validating a complete form</legend>
<p>
<label for="firstname">Firstname</label>
<input id="firstname" name="firstname" type="text" />
</p>
<p>
<label for="lastname">Lastname</label>
<input id="lastname" name="lastname" type="text" />
</p>
<input class="submit" type="submit" value="Submit"/>
</body>
Trailing commas (,) are illegal in JavaScript. When you do something like this:
rules: {
firstname: 'required',
lastname: 'required',
}
the JavaScript engine will think that }, is the next item in the rules object.
You need to do something like this:
rules: {
firstname: 'required',
lastname: 'required' // <-- no comma at end
}