how to validate a form tab wise, written in multiple tabs? - javascript

I have divided my form into 3 tabs and and when I click on next button it moves to the next tab and finally in the last tab when submit is clicked the whole form is getting validated which is also correct but my problem is that when I click next it must move to next tab only when the current tab validations are true.
Here is my form
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.13.0/jquery.validate.min.js"></script>
<form name="registration_form" id="registration_form" action="save.php" method="post">
<div id="tabs">
<ul>
<li>Basic Details</li>
<li>Employee Details</li>
<li>Address</li>
</ul>
<div id="tabs-1">
<div class="field">
<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" />
</div>
<div class="field">
<label>Age</label>
<input type="text" name="age" id="age"/>
</div>
<div class="field">
<input value="Next" type="button" id="next-1" name="1"/>
</div>
</div>
<div id="tabs-2">
<div class="field">
<label>Company</label>
<input type="text" name="company" id="company">
</div>
<div class="field">
<label>Designation</label>
<select name="designation" >
<option value="software developer">software developer</option>
<option value="software analyst">software analyst</option>
<option value="tester">tester</option>
</select>
</div>
<div class="field">
<label>Annual income</label>
<input type="text" name="income" id="income"> in Rupees
</div>
<div class="field">
<input value="Next" type="button" id="next-2" name="2" />
</div>
</div>
<div id="tabs-3">
<div class="field">
<label>Address</label>
<input type="text" name="address" id="address"
</div>
<div class="field">
<input type="submit" name="submit" value="SUBMIT" id="reg_submit" />
</div>
</div>
</div>
</form>
Javascript Validation code is
<script type="text/javascript">
$( "#tabs" ).tabs();
var validator = $("#registration_form").validate({ rules: {
first_name: {
required: true,
maxlength:30,
},
last_name: {
required: true,
maxlength:30,
},
age: {
digits:true,
},
company: {
required: true,
},
designation: {
required: true,
},
income: {
digits:true,
},
address: {
maxlength:100,
},
},
messages: {
first_name: {
required: "Please enter First Name",
maxlength: "maximum 30 characters are allowed",
},
last_name: {
required: "Please enter Last Name",
maxlength: "maximum 30 characters are allowed",
},
age: {
digits: "Enter only digits",
},
Company: {
required: "Please enter Company",
},
designation: {
required: "Please Select Designation",
},
income: {
digits: "Enter only digits",
},
address: {
maxlength: "Maximum of 100 characters are allowed",
},
}
});
// I have seen some examples in stack overflow and tried as below, but it is not working
var tabs = $("#tabs").tabs();
$('[id^=next-]').click(function() {
var tabid = $(this).attr('name');
var valid = true;
var i = 0;
var $inputs = $(this).children("div").find("input");
$inputs.each(function() {
if (!validator.element(this) && valid) {
validator.focusInvalid();
valid = false;
}
});
if (valid) {
var tabId = $(this).attr('name');
$( "#tabs" ).tabs( "option", "active", tabId );
}
});
$("input[id=reg_submit]").click(function() {
$(this).parents("form").submit();
});
please help,
Thanks

var next1 = false;
var next2 = false;
var next3 = false;
$('#next-1').on('click', function(){
//validate your inputs fields
var next1 = true;// assign true if validation is correct.
});
$('#next-2').on('click', function(){
//validate your inputs fields
var next2 = true;// assign true if validation is correct
});
$('#next-3').on('click', function(){
//validate your inputs fields
var next3 = true;// assign true if validation is correct
if((next1 == 'true') && (next2 == 'true') && (next3 == 'true'))
{
//submit form
}
})
try this example
Or Make three forms,

Related

jQuery validate plugin working only on last shown div [duplicate]

This question already exists:
jQuery show/hide form with jQuery validate plugin working on last shown div only
Closed 4 years ago.
I am trying to validate my form that is a jQuery show/hide form. jQuery validate plugin only validates my last input on the last div (input type file). I can currently upload an image and submit the form successfully with the remaining inputs empty.
Below is the third div and when i click post ad with no inputs filled in, "This field is required" is shown.
Below is the first div with no validation messages
Below is the second div with no validation messages
Here is my form:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Zootopia</title>
<script src="http://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>
</head>
<body>
<form id="ad_form" method="post">
<div id="ad_form_section1">
<div class="form-group">
<label for="ad_title">Ad Title</label>
<input type="text" class="form-control stored" id="ad_title" placeholder="e.g. German Sheperd puppy - 4 months old" name="ad_title" required>
</div>
<div class="form-group">
<label for="description">Describe what you're offering</label>
<textarea class="form-control stored" id="description" rows="6" placeholder="e.g. Owner supervised visits, minimum 1hr bookings, play with my german sheperd puppy in my backyard" name="description" required></textarea>
</div>
<button type="button" id="ad_section2" class="btn btn-primary"> Next </button>
</div>
<div id="ad_form_section2">
<div class="form-group">
<label for="location"> Location</label>
<input type="text" id="location_ad" class="form-control stored" placeholder="location" name="location" required/>
</div>
<div class="form-group">
<label for="price">Price</label>
<input type="text" id="price" class="form-control stored" name="price" placeholder="$0.00" required/>
</div>
<button type="button" id="back_section1" class="btn btn-primary"> Back </button>
<button type="button" id="ad_section3" class="btn btn-primary"> Next </button>
</div>
<div id="ad_form_section3">
<div>
<label> Select pet pictures</label>
<input type="file" name="multiple_files[]" id="multiple_files" multiple required/>
</div>
<button type="button" id="back_section2" class="btn btn-primary"> Back </button>
<input type="hidden" name="action_type" value="add" />
<input type="submit" id="ad_button" class="btn btn-primary" value="Post ad" />
</div>
</form>
Here is my JavaScript:
$(document).ready(function(){
$("#ad_section2").click(function(){
$("#ad_form_section1").hide();
$("#ad_form_section2").show();
});
$("#back_section1").click(function(){
$("#ad_form_section1").show();
$("#ad_form_section2").hide();
});
$("#ad_section3").click(function(){
$("#ad_form_section3").show();
$("#ad_form_section2").hide();
});
$("#back_section2").click(function(){
$("#ad_form_section2").show();
$("#ad_form_section3").hide();
});
$("#ad_form").validate({
rules:{
ad_title:{
required: true
},
description:{
required: true
},
location:{
required: true
}
},
messages:{
ad_title: {
required: "please enter an ad title"
},
description: {
required: "please enter a description"
},
location: {
required: "please enter a location"
}
},
submitHandler: function(form) {
var petID = $( "#pet_ad option:selected" ).val();
var addAdUrl = "../../controller/post_ad_process.php?petID=" + petID;
$(form).ajaxSubmit({
url:addAdUrl,
type:"post",
datatype: 'json',
success: function(result){
if(result.petAd == false){
alert("Pet ad already exists!");
}else{
alert("Ad posted!");
$('#image_table').hide();
}
},
error: function(error) {
alert("Error");
}
});
}
});
})
Here is my CSS:
#ad_form_section2,
#ad_form_section3{
display: none;
}
You need to add a condition before you show/hide next fields
if ( $('field-id').valid() ) {
// Code
}
For example:
$("#ad_section2").click(function(){
if ($('#ad_title').valid() && $('#description').valid()) {
$("#ad_form_section1").hide();
$("#ad_form_section2").show();
}
});
Also, don't forget to set character encoding to avoid characters range error, Add the following code just below <head> tag:
<meta charset="UTF-8">
Form Example:
$(document).ready(function(){
$("#ad_form").validate({
rules:{
ad_title:{
required: true,
minlength: 3, // set minimum title length
},
description:{
required: true,
minlength: 10,
},
location:{
required: true
}
},
messages:{
ad_title: {
required: "please enter an ad title",
minlength: "Your title must be more than 3 characters!",
},
description: {
required: "please enter a description",
minlength: "Your description must be at least 10 characters long",
},
location: {
required: "please enter a location"
}
},
submitHandler: function(form) {
var petID = $( "#pet_ad option:selected" ).val();
var addAdUrl = "../../controller/post_ad_process.php?petID=" + petID;
$(form).ajaxSubmit({
url:addAdUrl,
type:"post",
datatype: 'json',
success: function(result){
if(result.petAd == false){
alert("Pet ad already exists!");
}else{
alert("Ad posted!");
$('#image_table').hide();
}
},
error: function(error) {
alert("Error");
}
});
}
});
$("#ad_section2").click(function(){
// Check if valid before show/hide
if ($('#ad_title').valid() && $('#description').valid()) {
$("#ad_form_section1").hide();
$("#ad_form_section2").show();
}
});
$("#back_section1").click(function(){
$("#ad_form_section1").show();
$("#ad_form_section2").hide();
});
$("#ad_section3").click(function(){
// Check if valid before show/hide
if ($('#location_ad').valid()) {
$("#ad_form_section3").show();
$("#ad_form_section2").hide();
}
});
$("#back_section2").click(function(){
$("#ad_form_section2").show();
$("#ad_form_section3").hide();
});
});
#ad_form_section2,
#ad_form_section3 {
display: none;
}
label.error {
color: red;
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>
<div class="container">
<form id="ad_form" method="post">
<div id="ad_form_section1">
<div class="form-group">
<label for="ad_title">Ad Title</label>
<input type="text" class="form-control stored" id="ad_title" placeholder="e.g. German Sheperd puppy - 4 months old" name="ad_title">
</div>
<div class="form-group">
<label for="description">Describe what you're offering</label>
<textarea class="form-control stored" id="description" rows="6" placeholder="e.g. Owner supervised visits, minimum 1hr bookings, play with my german sheperd puppy in my backyard" name="description" required></textarea>
</div>
<button type="button" id="ad_section2" class="btn btn-primary"> Next </button>
</div>
<div id="ad_form_section2">
<div class="form-group">
<label for="location"> Location</label>
<input type="text" id="location_ad" class="form-control stored" placeholder="location" name="location" required/>
</div>
<div class="form-group">
<label for="price">Price</label>
<input type="text" id="price" class="form-control stored" name="price" placeholder="$0.00" required/>
</div>
<button type="button" id="back_section1" class="btn btn-primary"> Back </button>
<button type="button" id="ad_section3" class="btn btn-primary"> Next </button>
</div>
<div id="ad_form_section3">
<div>
<label> Select pet pictures</label>
<input type="file" name="multiple_files[]" id="multiple_files" multiple required/>
</div>
<button type="button" id="back_section2" class="btn btn-primary"> Back </button>
<input type="hidden" name="action_type" value="add" />
<input type="submit" id="ad_button" class="btn btn-primary" value="Post ad" />
</div>
</form>
</div>
More examples from documentation
By default the plugin is going to ignore any/all fields that are hidden. You have to set to the ignore option to "nothing".
$("#ad_form").validate({
ignore: [], // ignore nothing, validate everything
rules:{
ad_title:{ ....
If you're expecting validation when you show/hide sections of the form, that's not how it works. You're going to have to programmatically trigger validation on the relevant fields as you click back and forth. Use the .valid() method for this.
However, multi-step validation can quickly get tedious so you may have to re-think your entire approach. I personally like to enclose each section within its own set of <form></form> tags so I can control validation on each step separately.
Here's one example:
https://stackoverflow.com/a/20481497/594235

How to disable submit button after click submit button

I have created forms using php and using jquery for validation.What i exactly need is if validation successful on submit button, disable the submit button till submission gets over.Here is my code:
if(document.location.pathname == "/contact-us"){
$("#form-contact-user").validate({
ignore: [],
rules: {
name:{
required: true
},email: {
email: true
},
phne: {
phnDash: true
},
zip: {
zipcode: true
}
},
errorPlacement: function(error, element) {
if (element.attr("type") == "checkbox") {
error.appendTo( element.parent().parent().parent(".form-checkboxes"));
}
else if (element.attr("name") == "mailing_address")
{
error.appendTo(element.parent().parent().parent());
}
else{
error.insertAfter(element);
}
}
});
Try this:
$('#btnId').attr('disabled', true);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="submit" id="btnId" value="Submit">
I hope this is what you are looking for,
$('#submitBtn').click(function(event) {
//event.preventDefault();
$(this).attr('disabled', true);
//Perform Validation
//if(valid) {
// $("#form-contact-user").submit();
//}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="submit" id="submitBtn" value="Submit">
According to the documentation you can use:
submitHandler (default: native form submit):
Callback for handling the actual submit when the form is valid.
ANSWER UPDATED
From your comment:
Getting the following error:-Uncaught TypeError: Cannot read property 'call' of undefined
This message depends on your rules. Because I don't know anything about your
html I can also assume a possible structure in the following snippet:
$("#form-contact-user").validate({
debug: true,
rules: {
name: {
required: true,
minlength: 2
},
email: {
required: true
},
phone: {
required: true
},
zip: {
required: true
}
},
errorPlacement: function (error, element) {
if (element.attr("type") == "checkbox") {
error.appendTo(element.parent().parent().parent(".form-checkboxes"));
}
else if (element.attr("name") == "mailing_address") {
error.appendTo(element.parent().parent().parent());
}
else {
error.insertAfter(element);
}
},
submitHandler: function(form) {
// do other things for a valid form
$(form).find(':submit').prop('disabled', true);
setTimeout(function() {
form.submit();
}, 1000);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.validation/1.16.0/jquery.validate.min.js"></script>
<form id="form-contact-user" method="get" action="">
<fieldset>
<legend>Please provide your name, email address, phone number and zipcode</legend>
<p>
<label for="name">Name (required, at least 2 characters)</label>
<input id="name" name="name" type="text">
</p>
<p>
<label for="email">E-Mail (required)</label>
<input id="email" type="email" name="email">
</p>
<p>
<label for="phone">Phone Number (required)</label>
<input id="phone" type="text" name="phone">
</p>
<p>
<label for="zip">Zip code (required)</label>
<textarea id="zip" name="zip"></textarea>
</p>
<p>
<input class="submit" type="submit" value="Submit">
</p>
</fieldset>
</form>

Jquery Validate Form issue while split by 2 screen

I'm using the JQuery validate for my contact form. It was a single page form. But right now its split by 2 set. First set has few fields with a continue button. Then second set will be given by continue button. The continue btn validating without an issue. But it doesn't give the alert like the final submit btn.
Can you help me to resolve this
My Markup
<form name="contact" id="contact" method="post" action="http://action.com">
<div id="form-fields">
<!-- Form Step One -->
<div id="form_step1">
<div class="form-row">
<label class="request_label">Program of Interest</label>
<select id="CurriculumID" name="CurriculumID">
<option selected="selected" value="">What program would you like to study</option>
</select>
<br />
</div>
<div class="form-row">
<label class="request_label">First Name</label>
<input name="firstname" id="firstname" type="text" title="First Name" />
<br />
</div>
<div class="form-row">
<label class="request_label">Last Name</label>
<input name="lastname" id="lastname" type="text" title="Last Name" />
<br />
</div>
<!-- CLOSING (FIRST NAME AND LAST NAME) -->
<div class="req_btn_wrapper">
<a href="javascript:void(0)" id="next">
<img src="images/next_btn.png">
</a>
</div>
</div>
<!-- Form Step Two -->
<div id="form_step2">
<div class="form-row">
<label class="request_label">Email</label>
<input name="email" id="email" type="text" title="Email" />
<br />
</div>
<div class="form-row">
<div class="split-form-row">
<label class="request_label">Phone</label>
<input name="dayphone" id="dayphone" class="form_phone" type="text" onkeypress="return numbersonly(this, event)" title="Phone" />
<br />
</div>
<div class="split-form-row">
<label class="request_label">Zip Code</label>
<input name="zip" id="zip" class="form_zip" type="text" title="Zip Code" />
<br />
</div>
<div id="cityStateInput">
<input name="city" id="city" type="text" title="City" placeholder="City" />
<br />
<select name="state" id="state">
<option selected="selected" value="">Select a State:</option>
<option value="N/A">Orange</option>
<option value="N/A">lorem</option>
</select>
<br />
</div>
</div>
<div class="form-row">
<label class="request_label">Year</label>
<select name="gradyear" id="gradyear">
<option selected="selected" value="">Please Select</option>
<option value="2017">2017</option>
<option value="2016">2016</option>
<option value="2015">2015</option>
<option value="2014">2014</option>
</select>
</div>
<!-- Radio -->
<div class="radio_row">
<p id="military" class="military_label">Are you working in the military?</p>
<div class="radio_option">
<input type="radio" name="verify" value="Yes"><span id="yes1" for="yes">Yes</span>
</div>
<div class="radio_option">
<input type="radio" name="verify" value="No" checked="checked"><span id="no1">No</span>
</div>
</div>
<!-- Radio -->
<div class="clear"></div>
<!-- CLOSING CLEAR -->
<div class="req_btn_wrapper">
<input name="submit" id="submit" type="image" src="images/btn_submit_request.png" value="" />
</div>
</div>
</form>
My Js script
// Validate signup form on keyup and submit
$("#contact").validate({
ignore: ":hidden",
onclick: false,
onfocusout: false,
onsubmit: true,
onkeyup: false,
onkeydown: false,
rules: {
// Insert fields from the form
email: {
email: true
},
zip: {
minlength: 5,
required: true,
checkLabel: true,
zipUS: true
},
city: {
checkLabel: true,
required: true
},
dayphone: {
required: true,
checkPhoneValue: true
},
state: {
required: true
},
firstname: {
required: true,
checkLabel: true
},
lastname: {
required: true,
checkLabel: true
},
},
messages: {
// Place custom error messages
CurriculumID: "Please select a program.",
firstname: "Please enter your first name.",
lastname: "Please enter your last name.",
dayphone: "Please enter a valid phone number.",
email: "Please enter a valid email address.",
zip: "Please enter a valid Zip code.",
gradyear: "Please select H.S. graduation year.",
city: "Please enter your city.",
state: "Please select your state."
},
// Error placement
showErrors: function(errorMap, errorList) {
try {
if (submitted) {
var summary = "Please fix the following: \n\n";
$.each(errorList, function() {
summary += " - " + this.message + "\n";
});
alert(summary);
submitted = false;
}
//this.defaultShowErrors();
} catch (err) {
Raven.captureException(err);
}
},
invalidHandler: function(form, validator) {
try {
submitted = true;
} catch (err) {
Raven.captureException(err);
}
}
}); // END FORM VALIDATION
$(document).ready(function() {
$('#form_step2').hide();
var validateStep1 = function() {
var isValid_1 = $('#CurriculumID').valid();
var isValid_2 = $('#firstname').valid();
var isValid_3 = $('#lastname').valid();
if (isValid_1 && isValid_2 && isValid_3) {
$('#form_step1').hide();
$('#form_step2').show();
return false;
}
}
// Show step 2
$('#next').click(function() {
validateStep1();
});
$('#back-button').click(function() {
$('#form_step1').show();
$('#form_step2').hide();
});
// Check input value against inline label
jQuery.validator.addMethod("checkLabel", function(value, element) {
return this.optional(element) || value != element.title;
}, "Please enter a value.");
})
You have a couple issues that could break the expected behavior of the jQuery Validate plugin...
$("#contact").validate({
ignore: ":hidden",
onclick: false,
onfocusout: false,
onsubmit: true, // <- NEVER set to 'true'
onkeyup: false,
onkeydown: false, // <- No such thing
....
There is absolutely no such thing called onkeydown. Please refer to the documentation for all available options.
The onsubmit option must never be set to true as this breaks the built-in onsubmit function. This option can only be set to false or an over-riding function. If you want to keep the default submit functionality un-altered, then you must remove the onsubmit option from your .validate() method.
See: jqueryvalidation.org/validate/#onsubmit
"Set to false to use only other events for validation.
Set to a Function to decide for yourself when to run validation.
A boolean true is not a valid value".
The continue btn validating without an issue. But it doesn't give the alert like the final submit btn.
As far as your issue, you need to look at your JavaScript error console.
ReferenceError: Can't find variable: submitted
I removed the if (submitted) conditional within showErrors and got your "next" button working...
DEMO: http://jsfiddle.net/vpgmnLg0/

JQuery validate not showing error

for some reason having issues with JQuery validate even though I have used similar code previously. I have a simple form.
<form id="emailform" class="form-horizontal emailType" role="form">
<div class="form-group">
<label for="inputTitle" class="col-lg-4 control-label">Title</label>
<div class="col-lg-8">
<select class="form-control" id="inputTitle" name="inputTitle">
<option value="">Please select...</option>
<option value="Mr">Mr</option>
<option value="Mrs">Mrs</option>
</select>
</div>
</div>
<div class="form-group">
<label for="inputName" class="col-lg-4 control-label">First Name(s)</label>
<div class="col-lg-8">
<input type="text" class="form-control" id="inputName" name="inputName" placeholder="First Name(s)">
</div>
</div>
<div class="form-group">
<label for="inputSurname" class="col-lg-4 control-label">Surname</label>
<div class="col-lg-8">
<input type="text" class="form-control" id="inputSurname" name="inputSurname" placeholder="Surname">
</div>
</div>
<div class="form-group">
<label for="inputMethod" class="col-lg-4 control-label">Delivery Method</label>
<div class="col-lg-8" id="radioAlign">
<input type="radio" value="email" id="inputMethod" checked><span id="emailText">Email</span>
</div>
</div>
<div class="form-group">
<label for="inputEmail" class="col-lg-4 control-label">Email</label>
<div class="col-lg-8">
<input type="email" class="form-control" id="inputEmail" name="inputEmail" placeholder="Your Email">
</div>
</div>
<div class="form-group">
<label for="inputLinks" class="col-lg-4 control-label">Link to be sent</label>
<div class="col-lg-8">
<select class="form-control" id="inputLinks" name="inputLinks">
<option value="img/default.jpg">Please select...</option>
<option value="img/placeholder.jpg">Email1</option>
<option value="img/placeholder2.jpg">Email2</option>
</select>
</div>
</div>
<div class="form-group">
<div class="col-lg-offset-2 col-lg-10">
<button type="submit" class="btn btn-default">
Send Message
</button>
</div>
</div>
</form>
<div id="error"></div>
I then have my validation.
$.validator.addMethod(
"notEqualTo",
function(elementValue,element,param) {
return elementValue != param;
},
"Value cannot be {0}"
);
$.validator.addMethod("myCustomRule", function(value, element) {
return /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{1,}))$/.test(value);
}, "Please enter a valid email");
var validator = $("#emailform").validate({
errorPlacement: function (error, element) {
$(element)
.closest("form")
.find("#error")
.append(error);
},
rules: {
inputTitle: {
required: true,
notEqualTo: "Please select..."
},
inputName: {
required: true,
minlength: 1
},
inputSurname: {
required: true,
minlength: 1
},
inputEmail: {
required: true,
myCustomRule: true,
minlength: 5,
email: true
},
inputLinks: {
required: true,
notEqualTo: "Please select..."
}
},
messages: {
inputName: {
minlength: jQuery.validator.format("Please enter a valid name")
},
inputSurname: {
minlength: jQuery.validator.format("Please enter a valid surname")
},
inputEmail: {
minlength: jQuery.validator.format("Your email address is to short")
}
},
submitHandler: function(){
//Do success stuff here
return true;
},
invalidHandler: function(event,validator) {
//do error stuff here
return false;
}
});
If I submit the form, my error message does not display. Instead, the input gets highlighted with a blue border.
Is there any reason my errors do not display?
Thanks
I have update your validation massage code;
Please check this,
$.validator.addMethod(
"notEqualTo",
function(elementValue,element,param) {
return elementValue != param;
},
"Value cannot be {0}"
);
$.validator.addMethod("myCustomRule", function(value, element) {
return /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{1,}))$/.test(value);
}, "Please enter a valid email");
var validator = $("#emailform").validate({
errorPlacement: function (error, element) {
$(element)
.closest("form")
.find("#error")
.append(error);
},
rules: {
inputTitle: {
required: true,
notEqualTo: "Please select..."
},
inputName: {
required: true,
minlength: 1
},
inputSurname: {
required: true,
minlength: 1
},
inputEmail: {
required: true,
myCustomRule: true,
minlength: 5,
email: true
},
inputLinks: {
required: true,
notEqualTo: "Please select..."
}
},
messages: {
inputName: {
minlength: jQuery.validator.format("Please enter a valid name")
},
inputSurname: {
minlength: jQuery.validator.format("Please enter a valid surname")
},
inputEmail: {
minlength: jQuery.validator.format("Your email address is to short")
}
},
errorPlacement: function (label, element) { // render error placement for each input type
$('<span class="error"></span>').insertAfter(element).append(label)
var parent = $(element).parent('.input-with-icon');
parent.removeClass('success-control').addClass('error-control');
},
highlight: function (element) { // hightlight error inputs
var parent = $(element).parent();
parent.removeClass('success-control').addClass('error-control');
},
unhighlight: function (element) { // revert the change done by hightlight
var parent = $(element).parent();
parent.removeClass('error-control').addClass('success-control');
},
submitHandler: function(){
//Do success stuff here
return true;
},
invalidHandler: function(event,validator) {
//do error stuff here
return false;
}
});
does it work or not? let me know

Form is not validate using validate.min.js

Hi I succeed to make this code works but I don't know why this code is not working anymore anyone can help please on this?
Here this is my form
<form action="CreateUser" method="POST" id="subscribe">
<br>
<div class="form-group">
<div class="input-group">
<span class="input-group-addon"><b>#</b></span>
<label for="mail"></label>
<input type="text" class="form-control" name="mail" id="mail" placeholder="Adresse mail">
</div>
</div>
<div class="form-group">
<div class="input-group">
<span class="input-group-addon"><span class="fa fa-user"></span></span>
<label for="firstname"></label>
<input type="text" class="form-control" name="firstname" id="firstname" placeholder="Entrez votre prenom">
</div>
</div>
<div class="form-group">
<div class="input-group">
<span class="input-group-addon"><span class="fa fa-user"></span></span>
<label for="name"></label>
<input type="text" class="form-control" name="name" id="name" placeholder="Entrez votre nom">
</div>
</div>
<div class="form-group">
<div class="form-group">
<div class="input-group">
<span class="input-group-addon"><span class="fa fa-lock"></span></span>
<label for="inputPassword"></label>
<input id="inputPassword" name="inputPassword" type="password" class="form-control" placeholder="Mot de passe">
</div>
</div>
<div class="input-group">
<span class="input-group-addon"><span class="fa fa-lock"></span></span>
<label for="txtConfirmPassword"></label>
<input id="txtConfirmPassword" name="txtConfirmPassword" type="password" class="form-control" placeholder="Retapez votre mot de passe">
</div>
</div>
<br>
<div class='modal-footer'>
<button class="btn btn-lg btn-success btn-block" name="submit" id="register" >Creer votre compte</button>
</div>
</form>
And here this the validate function I did:
<script>
$.validator.setDefaults({
debug: true,
success: "valid",
highlight: function (element) {
$(element).parent().removeClass('has-success').addClass('has-error');
},
unhighlight: function (element) {
$(element).parent().removeClass('has-error').addClass('has-success');
},
errorElement: 'span',
errorClass: 'text-danger',
errorPlacement: function (error, element) {
if (element.parent('.input-group').length) {
error.insertAfter(element.parent());
} else {
error.insertAfter(element);
}
}
});
$.validator.addMethod("onlyletters", function (value, element) {
return this.optional(element) || /^[a-zA-ZáàâäãåçéèêëíìîïñóòôöõúùûüýÿæœÁÀÂÄÃÅÇÉÈÊËÍÌÎÏÑÓÒÔÖÕÚÙÛÜÝŸÆŒ._\s-]+$/i.test(value);
}, "Please enter letters only.");
$.validator.addMethod("passwd", function (value, element) {
return this.optional(element) || /^[a-zA-Z0-9]+$/i.test(value);
}, "Please enter letters and numbers only.");
$('#subscribe').validate({
rules: {
inputPassword: {
required: true,
minlength: 6,
maxlength: 12,
passwd: true
},
txtConfirmPassword: {
required: true,
minlength: 6,
maxlength: 12,
passwd: true,
equalTo: "#inputPassword"
},
mail: {
required: true,
email: true
},
firstname: {
required: true,
maxlength: 20,
onlyletters: true
},
name: {
required: true,
maxlength: 20,
onlyletters: true
}
},
messages: {
inputPassword: {
required: "Password is required",
minlength: "Your password must have 6 characters."
},
txtConfirmPassword: {
required: "Password is required",
minlength: "Your password must have 6 characters.",
equalTo: "Your password doesn't match."
},
mail: {
required: "Email is required",
email: "Your mail address should be like user#example.com"
}
}
});
$('#register').click( function() {
// Error checking here.
if ($('div.error').is(':visible')) {
return false;
}else{
}
});
</script>
And the imported jquery plugin
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="http://jqueryvalidation.org/files/dist/jquery.validate.min.js"></script>
<script src="http://jqueryvalidation.org/files/dist/additional-methods.min.js"></script>
The plugin are imported from a previous page index.html and this form is loading from a modal
There is a problem on your .click() syntax, here is the working code in a JSFiddle.
Your error was a } and ) problem.
Your click event handler is not correct.
$('#register').click( function() {
// Error checking here.
if ($('div.error').is(':visible')) {
return false;
}else{
});// This needs to be removed!!!!!
}
});
Working code:
$('#register').click( function() {
// Error checking here.
if ($('div.error').is(':visible')) {
return false;
} else {
}
});

Categories