language based validation using jquery - javascript

I have created page in which I am having a language selection drop-down, upon selection a language, then the validation of the fields should be in that specific language. Lets say I am selecting Arabic, then validation should be in Arabic. I am using jQuery-Form-Validator plugin,but don't know how to switch the language based validation.
my code is as given below
JSFiddle
Html
Select Language:<select>
<option value="english">English</option>
<option value="arabic">Arabic</option>
</select>
<form action="" id="myForm">
<p>
Name:<input name="user" data-validation="length" data-validation-length="min5" data-validation-error-msg="Maximum Length is 5"/>
</p>
<p>
Email:<input type="text" data-validation="email" data-validation-error-msg="Invalid Email"/>
</p>
<div>
<input type="submit" value="Submit" />
</div>
</form>
Can anyone please tell me some solution for this

<!DOCTYPE html>
<html>
<head>
<META HTTP-EQUIV="Content-Language" charset="UTF-8">
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript" src="formValidator.js"></script>
<style>
.add{
}
</style>
</head>
<body>
See errors in your language :
<select id="lang" >
<option value="en">English</option>
<option value="ar">Arabic</option>
<option value="mr">Marathi</option>
<option value="hi">Hindi</option>
<!-- add more language option -->
</select>
<form action="" id="myForm">
<p>
Name:<input id="name" name="user" data-validation="length" data-validation-length="min5" data-validation-error-msg="Maximum Length is 5"/>
</p>
<p>
Email:<input id="email" type="text" data-validation="email" data-validation-error-msg="Invalid Email"/>
</p>
<div>
<input type="submit" value="Submit" />
</div>
</form>
<script>
var validations = {
"en" : {
"name" : "Maximum Length is 5",
"email" : "Invalid Email"
},
"ar" : {
"name" : "أقصى طول هو 5",
"email" : "بريد إلكتروني خاطئ"
},
"mr" : {
"name" : "कमाल लांबी 5",
"email" : "अवैध ईमेल"
},
"hi" : {
"name" : "अधिकतम लंबाई 5",
"email" : "अवैध ईमेल"
}
//add more errors in your language
};
$("#lang").on('change', function(){
var currLang = $('#lang option:selected').attr('value');
$("#name").attr('data-validation-error-msg',validations[currLang].name);
$("#email").attr('data-validation-error-msg',validations[currLang].email);
});
$.validate({
});
</script>
</body>
</html>

Here is my original suggestion, fixed - please note I added ID to the user and email
var msg = {
"ar": {
invalidEmail: 'بريد إلكتروني خاطئ',
maxLength: 'أقصى طول هو 5'
},
"en": {
invalidEmail: 'Invalid Email',
maxLength: 'Maximum Length is 5'
}
}
$(function () {
$.validate({});
$("#lang").on("change", function () {
var msgs = msg[this.value];
// NOTE using .data does NOT work!
$("#user").attr("data-validation-error-msg", msgs.maxLength);
$("#email").attr("data-validation-error-msg", msgs.invalidEmail);
}).change();
});
.error {
color:red;
}
.input-validation-error {
border:1px solid red;
}
h1 {
font-weight:bold;
}
#debug {
font-size:small;
}
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery-form-validator/2.2.1/jquery.form-validator.min.js"></script>
Select Language:
<select id="lang">
<option value="en">English</option>
<option value="ar">Arabic</option>
</select>
<form action="" id="myForm">
<p>Name:
<input id="user" name="user" data-validation="length" data-validation-length="min5" />
</p>
<p>Email:
<input id="email" name="email" type="text" data-validation="email" />
</p>
<div>
<input type="submit" value="Submit" />
</div>
</form>
Here another suggestion - please note I am using this plugin: http://jqueryvalidation.org/
var msg = {
ar: {
invalidEmail: 'بريد إلكتروني خاطئ',
maxLength: 'أقصى طول هو 5'
},
en: {
invalidEmail: 'Invalid Email',
maxLength: 'Maximum Length is 5'
}
}
$(function () {
$("#myForm").validate({
user: {
required: true,
length: 5
},
email: {
required: true,
email:true
}
});
$("#lang").on("change", function () {
var lang = this.value;
$("#user").rules("add", {
messages: {
required: msg[lang].maxLength,
length: msg[lang].maxLength
}
});
$("#email").rules("add", {
messages: {
required: msg[lang].invalidEmail,
email: msg[lang].invalidEmail
}
});
}).change();
});
.error {
color:red;
}
.input-validation-error {
border:1px solid red;
}
h1 {
font-weight:bold;
}
#debug {
font-size:small;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.10.0/jquery.validate.min.js"></script>
Select Language:
<select id="lang">
<option value="en">English</option>
<option value="ar" selected>Arabic</option>
</select>
<form action="" id="myForm">
<p>Name:
<input id="user" name="user" class="required" />
</p>
<p>Email:
<input name="email" id="email" class="required" type="text"/>
</p>
<div>
<input type="submit" value="Submit" />
</div>
</form>

$("select").on("change", function() {
$("#name-input").data("validation-error-msg", errorMsgInDiffLang);
});

Have you gone through this post on StackOverflow here this solution would make your life easier

Related

How to specify the validated field in jQuery-validate

I have 2 fields: Name Query and Date of Birth, while Name Query is mandatory and DoB isn't. I have the following form to show an validation message under the Name Query field:
var myForm = $("#myform").validate({
rules: {
NameQuery: "required",
DoBQuery: {
required: false
}
},
messages: {
NameQuery: "Please fill in name query field",
DoBQuery: ""
}
});
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.1.js"></script>
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.12.0/jquery.validate.js"></script>
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.12.0/additional-methods.js"></script>
<form id="myform" method="post" action="">
<div>
<label for="NameQuery">Name</label>
<input type="text" id="NameQuery" name="NameQuery">
</div>
<div>
<label for="DoBQuery">Date of Birth</label>
<input type="text" id="DoBQuery" name="DoBQuery">
</div>
<input type="submit" value="Search">
</form>
Now I'd like to add some styling to the Name Query field validation message. Some code was added to the snippet, notice that the <div class="error__input"></div> has to EXIST IN BOTH FIELDS like in the snippet
var myForm = $("#myform").validate({
rules: {
NameQuery: "required",
DoBQuery: {
required: false
}
},
messages: {
NameQuery: "Please fill in name query field",
DoBQuery: ""
},
errorElement : 'div',
errorLabelContainer: '.error__input'
});
.error__input{
min-height: 20px;
}
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.1.js"></script>
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.12.0/jquery.validate.js"></script>
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.12.0/additional-methods.js"></script>
<form id="myform" method="post" action="">
<div>
<label for="NameQuery">Name</label>
<input type="text" id="NameQuery" name="NameQuery">
<div class="error__input"></div>
</div>
<div>
<label for="DoBQuery">Date of Birth</label>
<input type="text" id="DoBQuery" name="DoBQuery">
<div class="error__input"></div>
</div>
<input type="submit" value="Search">
</form>
Now the validation message exists in both fields, I understand that jQuery-validate finds the error__input div and apply the class to it, but why does it add the message to the second field and how can I set the alert message to apply only on the first message while both <div class="error__input"></div> have to be there?
You want something like this, I guess:
var myForm = $("#myform").validate({
rules: {
NameQuery: "required",
DoBQuery: {
required: false
}
},
messages: {
NameQuery: "Please fill in name query field",
DoBQuery: ""
}
});
#myform .error {
display: block;
color: red;
}
#myform input {
display: inline;
}
#myform > div {
height: 50px;
}
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.1.js"></script>
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.12.0/jquery.validate.js"></script>
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.12.0/additional-methods.js"></script>
<form id="myform" method="post" action="">
<div>
<label for="NameQuery">Name</label>
<input type="text" id="NameQuery" name="NameQuery" style="display: inline-block;">
</div>
<div>
<label for="DoBQuery">Date of Birth</label>
<input type="text" id="DoBQuery" name="DoBQuery" style="display: inline-block;">
</div>
<input type="submit" value="Search">
</form>
You could use errorPlacement to put your error message next to the error element.
errorPlacement: function(error,element){
error.appendTo(element.next(".error__input"));
}
var myForm = $("#myform").validate({
rules: {
NameQuery: "required",
DoBQuery: {
required: false /* if it is not required, why you put here? You can simply not insert this input field in validate()'s rules. */
}
},
messages: {
NameQuery: "Please fill in name query field"
},
errorElement : 'div',
errorPlacement: function(error,element){
error.appendTo(element.next(".error__input"));
}
});
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.1.js"></script>
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.12.0/jquery.validate.js"></script>
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.12.0/additional-methods.js"></script>
<form id="myform" method="post" action="">
<div>
<label for="NameQuery">Name</label>
<input type="text" id="NameQuery" name="NameQuery">
<div class="error__input"></div>
</div>
<div>
<label for="DoBQuery">Date of Birth</label>
<input type="text" id="DoBQuery" name="DoBQuery">
<div class="error__input"></div>
</div>
<input type="submit" value="Search">
</form>
you should remove <div class="error__input"></div> tag after Date of Birth field

How to use showErrors function to show a centralized error message and change input border color

I am using the showError function with jQuery validate to output a single error message at the bottom of my form. The functionality of this is working. However, I have two small modifications I am trying to figure out.
How can I get the borders to change to a different color for the inputs with the errors.
Edit - I figured out #1 above. I just need to figure out #2.
Right now, if I fill in one input and then click into another input or anywhere else on the page, the error message '#formErrors` from the showErrors function populates. I only want it to populate when the user tries to submit the form.
Any ideas?
var send = false;
$('#catalogRequestForm').validate({
ignore: [],
rules: {
first_name: {
required: true,
minlength: 2
},
last_name: {
required: true,
minlength: 2
},
address1: {
required: true,
minlength: 5
},
city: {
required: true,
minlength: 2
}
},
errorPlacement: function() {
return false;
},
showErrors: function(errorMap, errorList) {
$('#formErrors').html('All required fields must be completed before you submit the form.');
this.defaultShowErrors();
},
submitHandler: function() {
submit();
},
});
#formErrors {
color: #b82222;
font-family: 'Nunito', sans-serif;
font-size: 1rem;
margin: 10px auto;
}
input.error {
border: 1px solid #b82222;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jquery.validate/1.16.0/jquery.validate.min.js"></script>
<form method="POST" id="catalogRequestForm">
<!-- Form Fields -->
<input type="text" class="input2" id="first_name" name="first_name" placeholder="First Name *">
<input type="text" class="input2 margRightN" id="last_name" name="last_name" placeholder="Last Name *">
<input type="text" class="input block" id="company" name="company" placeholder="Company Name">
<input type="text" class="input block" id="address1" name="address1" placeholder="Address 1 *">
<input type="text" class="input block" id="address2" name="address2" placeholder="Address 2">
<input type="text" class="input3" id="city" name="city" placeholder="City *">
<select class="input3" id="state" name="state">
<option value="">State *</option>
<option value="AL">Alabama</option>
</select>
<div id="formErrors"></div>
<input id="requestSubmit" class="button" type="submit" value="Request Catalog">
</form>
Right now, if I fill in one input and then click into another input or anywhere else on the page, the error message '#formErrors` from the showErrors function populates. I only want it to populate when the user tries to submit the form.
As per documentation for showErrors, it's also fired on focusout and keyup. If you only want that message to show up when you submit the form, then use the invalidHandler instead of showErrors.
Also, your submitHandler was missing the form argument so it would never be able to properly submit anything. Corrected below.
submitHandler: function(form) {
form.submit(); // default behavior
},
HOWEVER, this is exactly the default, so it's not even needed and submitHandler can be removed entirely in this case.
var send = false;
$('#catalogRequestForm').validate({
ignore: [],
rules: {
first_name: {
required: true,
minlength: 2
},
last_name: {
required: true,
minlength: 2
},
address1: {
required: true,
minlength: 5
},
city: {
required: true,
minlength: 2
}
},
errorPlacement: function() {
return false;
},
invalidHandler: function(event, validator) {
$('#formErrors').html('All required fields must be completed before you submit the form.');
}
});
#formErrors {
color: #b82222;
font-family: 'Nunito', sans-serif;
font-size: 1rem;
margin: 10px auto;
}
input.error {
border: 1px solid #b82222;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jquery.validate/1.16.0/jquery.validate.min.js"></script>
<form method="POST" id="catalogRequestForm">
<!-- Form Fields -->
<input type="text" class="input2" id="first_name" name="first_name" placeholder="First Name *">
<input type="text" class="input2 margRightN" id="last_name" name="last_name" placeholder="Last Name *">
<input type="text" class="input block" id="company" name="company" placeholder="Company Name">
<input type="text" class="input block" id="address1" name="address1" placeholder="Address 1 *">
<input type="text" class="input block" id="address2" name="address2" placeholder="Address 2">
<input type="text" class="input3" id="city" name="city" placeholder="City *">
<select class="input3" id="state" name="state">
<option value="">State *</option>
<option value="AL">Alabama</option>
</select>
<div id="formErrors"></div>
<input id="requestSubmit" class="button" type="submit" value="Request Catalog">
</form>

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

jQuery validate require_from_group error message location

I have successfully been able to use the code in
jsfiddle.net/y3qayufu/2/ to validate a group of fields but how can I display the error message in a specific location. I would like the error message to appear only once after the submit button has been pressed, preferably above the group, but possibly below.
Instead of this:
I would like this:
Thanks
Use jQuery validation errorPlacement function provided:
JsFiddle updated
$("#findproject_form").validate({
rules: {
....
},
errorPlacement: function(error, element) {
$('label.error').remove();
error.insertAfter("#submit_btn");
}
});
HTML:
<div class="searchbg" id="submit_btn" style="margin-right:0px;">
<input class="bgbttn" type="submit" name="submit" value="" />
</div>
Hi here is a fixed fiddle http://jsfiddle.net/bayahiassem/sdx4ru4s/2/
If you can't open it, here the updated code:
html Only added an id to the h3
<form id="findproject_form" method="post" action="{$BASE_URL}findproject">
<div class="bgtrans">
<h3 id="header">Search By</h3>
<div class="div_bg1">
<div class="searchbg">
<div class="seachbginputbg">
<input class="seachbginput validategroup" type="text" placeholder="Profession" id="Profession" name="Profession" value="" />
</div>
</div>
<div class="searchbg">
<div class="seachbginputbg">
<input class="seachbginput validategroup" type="text" placeholder="Location" id="Location1" name="Location1" value="" />
</div>
</div>
<div class="searchbg" style="margin-right:0px;">
<div class="seachbginputbg">
<input class="seachbginput validategroup" type="text" placeholder="Company" id="Company" name="Company" value="" />
</div>
</div>
<div class="clear"></div>
</div>
<div class="div_bg2">
<div class="searchbg">
<div class="seachbginputbg">
<input class="seachbginput validategroup" type="text" placeholder="Name" id="Name" name="Name" value="" />
</div>
</div>
<div class="searchbg">
<div class="seachbginputbg">
<input class="seachbginput validategroup" type="text" placeholder="Key Words" id="KeyWord" name="KeyWord" value="" />
</div>
</div>
<div class="searchbg" style="margin-right:0px;">
<input class="bgbttn" type="submit" name="submit" value="" />
</div>
<div class="clear"></div>
</div>
</div>
</form>
JS using errorPlacement :
$(document).ready(function () {
jQuery.validator.setDefaults({
debug: true,
success: "valid"
});
$("#findproject_form").validate({
rules: {
Profession: {
require_from_group: [1, ".validategroup"]
},
Location1: {
require_from_group: [1, ".validategroup"]
},
Company: {
require_from_group: [1, ".validategroup"]
},
Name: {
require_from_group: [1, ".validategroup"]
},
KeyWord: {
require_from_group: [1, ".validategroup"]
}
},
errorPlacement: function(error, element) {
console.log(error[0].innerText);
if(error[0].innerText == 'Please fill at least 1 of these fields.' && !errorshowed) {
error.insertAfter("#header");
errorshowed = true;
}
}
});
var errorshowed = false;
$.validator.addMethod("require_from_group", function (value, element, options) {
var $fields = $(options[1], element.form),
$fieldsFirst = $fields.eq(0),
validator = $fieldsFirst.data("valid_req_grp") ? $fieldsFirst.data("valid_req_grp") : $.extend({}, this),
isValid = $fields.filter(function () {
return validator.elementValue(this);
}).length >= options[0];
// Store the cloned validator for future validation
$fieldsFirst.data("valid_req_grp", validator);
// If element isn't being validated, run each require_from_group field's validation rules
if (!$(element).data("being_validated")) {
$fields.data("being_validated", true);
$fields.each(function () {
validator.element(this);
});
$fields.data("being_validated", false);
}
return isValid;
}, $.validator.format("Please fill at least {0} of these fields."));
});
Try this on submit u can put in function definition
var valid=0;
$(this).find('input[type=text], select').each(function(){
if($(this).val() != "") valid+=1;
});
if(valid==0)
{
$('#myDiv').html("please fil atleast one of these");
}

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/

Categories