Multiple language validation handling logic - javascript

I've a form with multiple languages eg: English, German, Chineese.
Each one contains three fields-
select list
heading textbox
textarea
completed the validation based on everything is mandatory logic.
My requirement has been changed now,
If user directly hit submit button without filling feilds everything should be highlighted.
If user add a field value of any of the lang, remaining blank fields of respective lang should be highlighted
eg: User added German heading value, remaining two fields of german only highlighted
Thanks in advance ;)

You can use depend function in jquery
How to use jquery validate "depends" on rules other than "required"?
<input type="text" name="text1" id="text1" class="form-control frm1">
<input type="text" name="text2" id="text2" class="form-control frm1">
<input type="text" name="text3" id="text3" class="form-control frm1">
In your jquery validation
text1: {
required: {
depends: function(element) {
return ($("#text2").val() == "" || $("#text3").val() == "" );
}
},
},
text2: {
required: {
depends: function(element) {
return ($("#text1").val() == "" || $("#text3").val() == "" );
}
},
},
text3: {
required: {
depends: function(element) {
return ($("#text1").val() == "" || $("#text2").val() == "" );
}
},
}
Hope now you understand something,

Related

Require one of two fields to be filled (either/or) in custom web form validate.js

So, I have these two form fields. Currently they are both 'required' as you may see. I am using standard validate.js the problem is I would like to change this to not be default required for each, but only the user has to do one; so basically either or should be required. Any approach ideas?
<label class="filebutton">
<span id="select">Select File</span><span><input name="Text1" type="file" id="upload" required></span>
</label>
<textarea class="form-control" name="Text2" rows="5" id="word_count" placeholder="What would you do with your 25th hour? [100 words max]" required></textarea>
<em>Total word count:</em> <span id="display_count">0</span> <em>words.</em> <em>Words left:</em> <span id="word_left">100</span>
<br>
attempt 1.)
function validateForm(){
var value1 = document.getElementById('upload').value;
var value2 = document.getElementById('word_count').value;
if( value1 != "" || value2 != "" ) {
return true;
}
alert("You must enter a value");
return false;
}
attempt 2.)
$("#form").validate({
rules: {
text1: {
require_from_group: [1, ".phone-group"]
},
text2: {
require_from_group: [1, ".phone-group"]
}
}
});

jQuery Validate: Validate that one field, or both fields of a pair are required

I have a form that I am trying to validate that has two fields:
<div class="entryForm">
<div class="formField">
<label for="fieldEmailAddress">Email address:</label>
<input type="email" name="fieldEmailAddress" id="fieldEmailAddress"/>
</div>
<div class="formField">
<label for="fieldMobileNumber">Mobile number:</label>
<input type="text" name="fieldMobileNumber" id="fieldMobileNumber"/>
</div>
</div>
Here's my jQuery Validation wireup:
<script type="text/javascript">
$(document).ready(function () {
$('#form1').validate({ rules: { fieldMobileNumber: { phoneUS: true } } });
});
</script>
What I'd like to do is add an additional validation rule that says: the form is not valid if both fieldEmailAddress and fieldMobileNumber are blank. In other words, I'd like to make it such that at least one of either fieldEmailAddress or fieldMobileNumber is required. It seems like most of the jQuery Validation custom methods are designed to only work for one field at a time - I need to validate both.
Any ideas?
You can bypass the Validate plugin and do a check like the following:
$("#form1").submit(function() {
var email = $('#fieldEmailAddress');
var phone = $('#fieldMobileNumber');
if(email.val() == '' && phone.val() == '') {
alert('Fill out both fields');
}
else if(email.val() == '') {
alert('Email, please...');
}
else if(phone.val() == '') {
alert('Phone, please...');
}
else {
alert('Yay!');
}
});
You simply need to include the additional-methods.js file and use the require_from_group method.
require_from_group: [x, '.class']
// x = number of items required from a group of items.
// .class = class assigned to every form element included in the group.
jQuery:
$(document).ready(function () {
$('#form1').validate({
rules: {
fieldMobileNumber: {
phoneUS: true,
require_from_group: [1, '.mygroup']
},
fieldEmailAddress: {
require_from_group: [1, '.mygroup']
}
},
groups: {
theGroup: 'fieldMobileNumber fieldEmailAddress'
}
});
});
Add class="mygroup" to each input you need to group together...
<input type="email" name="fieldEmailAddress" id="fieldEmailAddress" class="mygroup" />
And finally, optionally use the groups option to lump the messages into one...
groups: {
theGroup: 'fieldMobileNumber fieldEmailAddress'
}
Working DEMO: http://jsfiddle.net/CYZZy/
If you don't like where the validation message is placed, that's where you'd tweak it using the errorPlacement callback function.

Show hide div and script based on radio button

I'm trying to implement validation into my form being conditional. Basically if the user selects email radio option then email is going to be required, or if phone is selected then phone field would be required.
So far I've gotten this code to work, form submits and validation works fine. But if I switch to phone, then switch back to email, the validation is loaded so form won't submit if I haven't filled out both fields.
I have it set that way but basically trying to make it so if one field is selected then the other required. Any better ways to do this?
HTML:
<label>Method of Contact</label>
<label class="radio">
<input type="radio" name="group" value="ck1" checked/>
Email
</label><br />
<label class="radio"><input type="radio" name="group" value="ck2" />
Phone
</label>
<div id="emaildisp">
<label>Email</label>
<input id="emailv" name="email" type="email" />
</div>
<div id="phonedisp">
<label>Phone</label>
<input id="phonev" name="phone" type="text" />
</div>
Javascript:
$(function()
{
if (jQuery('input[value=ck2]:checked').length > 0)
{
jQuery('#phonedisp').show();
jQuery('#emaildisp').hide();
jQuery("#phonev").validate(
{
expression: "if (VAL) return true; else return false;",
message: "Please enter your phone number"
});
}
else
{
jQuery('#phonedisp').hide();
jQuery('#emaildisp').show();
jQuery("#emailv").validate(
{
expression: "if (VAL) return true; else return false;",
message: "Please enter your email"
});
}
jQuery('input[name=group]').change(function()
{
var selected = jQuery(this).val();console.log(selected);
if(selected == 'ck2')
{
jQuery('#phonedisp').show();
jQuery('#emaildisp').hide();
jQuery("#phonev").validate(
{
expression: "if (VAL) return true; else return false;",
message: "Please enter your phone number"
});
}
else
{
jQuery('#phonedisp').hide();
jQuery('#emaildisp').show();
jQuery("#emailv").validate(
{
expression: "if (VAL) return true; else return false;",
message: "Please enter your email"
});
}
});
});
Solution:
Thanks to the answers below, I came up with the solution. Key difference, I was not using jquery validation plugin, rather a different validation script. So I switched over, for beginners, just look it up you'll simply have to add link to the script in the header.
Next I gave the form an id, #myform. Then I have the ck1 and ck2 radio button their own respective ids, #ck1id and #ck2id. And using the below code, if the radio button is selected, then depending on the id selected, next part becomes validation required.
<script type='text/javascript'>
$(function(){
jQuery('input[name=group]').change(function() {
var selected = jQuery(this).val();console.log(selected);
if(selected == 'ck2'){
jQuery('#phonedisp').show();
jQuery('#emaildisp').hide();
} else {
jQuery('#phonedisp').hide();
jQuery('#emaildisp').show();
}
});
jQuery('input[name=group]').triggerHandler('change');
});
</script>
<script>
$(function(){
// validate signup form on keyup and submit
$("#myform").validate({
rules: {
group: "required",
email:
{
required: '#ck1id:checked',
email: true
},
phone:
{
required: '#ck2id:checked',
digits: true
}
},
messages: {
group: "Please select one",
email: "Please enter your email.",
phone: "Please enter your phone."
}
});
});
</script>
You need to remove the previously added validation from the other fields those are not required. If you need phone remove validation from email and vice versa.
You can follow two way, either remove validation or ignore the validation.
1. Removing the validation:
jQuery("#emailv").rules('remove');
or
jQuery("#phonev").rules('remove');
2. Ignore validation:
jQuery("#emailv").validate({
ignore: "#emailv"
});
or
jQuery("#phonev").validate({
ignore: "#phonev"
});
Check if this helps you.
Use .rules("remove") to remove jquery validation.
$(function(){
jQuery('input[name=group]').change(function() {
var selected = jQuery(this).val();console.log(selected);
if(selected == 'ck2'){
jQuery('#phonedisp').show();
jQuery('#emaildisp').hide();
jQuery("#emailv").rules("remove"); //remove the other field validation
jQuery("#phonev").validate({
expression: "if (VAL) return true; else return false;",
message: "Please enter your phone number"
});
} else {
jQuery('#phonedisp').hide();
jQuery('#emaildisp').show();
jQuery("#phonev").rules("remove"); //remove the other field validation
jQuery("#emailv").validate({
expression: "if (VAL) return true; else return false;",
message: "Please enter your email"
});
}
});
jQuery('input[name=group]').triggerHandler("change");
});
I see that you have duplicated code, just remove it and use jQuery('input[name=group]').triggerHandler("change"); to trigger it when page first loads

jquery form validation using groups

I have an order form, one part of the form is the address. It contains Company, Street-Address, ZIP, Town, Country with a simple jquery form validation with every field required, and ZIP validated for number. Now what I want is to group them and only have one field showing "valid address" on success, or "address wrong" on error.
This is a part of my js code:
$("#pageform").validate(
{
messages: {
company_from: addressError, //addressError is a JS var for the error message
street_from: addressError,
zip_from: addressError,
town_from: addressError,
country_from: addressError
},
groups: {
from: "company_from street_from zip_from town_from country_from"
},
errorPlacement: function(error, element) {
if (element.attr("name") == "company_from"
|| element.attr("name") == "street_from"
|| element.attr("name") == "zip_from"
|| element.attr("name") == "town_from"
|| element.attr("name") == "country_from"
)
{
$("#error_from").append(error);
}
},
success: function(label) {
var attribute = $(label[0]).attr("for");
$(".err-ok-" + attribute + " .ok").css("display", "block").css("visibility", "visible");
}
}
);
This is a part of the corresponding HTML code:
<input type="text" name="company_from" id="company_from" class="required default input-s8" maxlength="255" />
<input type="text" name="street_from" id="street_from" class="required default input-s8" maxlength="255" />
<input type="text" name="zip_from" id="zip_from" class="required digits default input-s8" maxlength="5" onblur="checkCalculation()" />
<input type="text" name="town_from" id="town_from" class="required default input-s8" maxlength="255" />
<!-- and a select list for the country -->
You do not need to take a closer look on how I show the error and so on, my problem is, that I do not know when to show the error label and when the success label. When I enter a letter for the ZIP code, my errorPlacement function and the success function is called (and the errorPlacement first), so I guess it's always calling the success if there is at least one field correct.
Please ask if there are any questions, and I am pretty sure there are... :-)
Add rules
rules: {
company_from: "required",
company_from: "required",
zip_from: "required",
town_from:"required",
country_from:"required"
},

Figuring out form validation to validate a value across multiple inputs

I'm using the jQuery form wizard plugin. I have 20 questions that each have three answers. Each answer can have a weight. For each question, the total weight of the answers must be equal to 10.
<fieldset id="first" class="step">
<input type="text" size="2" maxlength="2" value="" name="question1[]" class="required"/>A: Inspiring others with a compelling vision for change.<br />
<input type="text" size="2" maxlength="2" value="" name="question1[]" />B: Engaging others to buy-into the change.<br />
<input type="text" size="2" maxlength="2" value="" name="question1[]" />C: Executing a project plan and managing accountabilities.<br />
<label for="question1[]" class="error" style="display:none;">Your values must add up to 10!</label>
</fieldset>
This is basically a personality assessment. Let's say I feel A and C do not apply, I'd enter in 10 for A.
Is there any way to check to see if each field set is adding up to 10 and if not send an error message?
I am using the jQuery validation plugin, but this seems to be a bit too specific, as I know it checks for numbers, etc.
I've tried to add something along the following to even get a required check to pass, but I'm not sure where to go from here:
$(document).ready(function() {
$("#Form").validate({
submitHandler: function(form) {
form.submit();
}
});
$("#Form input[name='question1']").each(function() {
$(this).rules("add", {
required: true,
maxlength: 2,
messages: {
required: "Required",
minlength: jQuery.format("Max length of {2} characters.")
}
});
});
});
I have also found that jQuery validate had to have a function edited to accomodate arrays. I've changed the following function:
checkForm: function() {
this.prepareForm();
for (var i=0, elements=(this.currentElements = this.elements()); elements[i]; i++ ) {
if (this.findByName(elements[i].name).length != undefined &&
this.findByName( elements[i].name ).length > 1) {
for (var cnt = 0; cnt < this.findByName( elements[i].name ).length; cnt++) {
this.check( this.findByName( elements[i].name )[cnt] );
}
}
else {
this.check( elements[i] );
}
}
return this.valid();
}
I have also tried this:
$(document).ready(function(){
$("#Form").validate({
rules: {
question1: {
required: true
}
},
submitHandler: function(form) {
form.submit();
}
});
});
None of this seems to work to even give me a 'required' error. There are no errors in console. I need to validate this on each question as the "next" button is pressed. The next button does have type=submit, so it theoretically should at least see that I said question 1 must be required but to no avail.
I also tried this:
$().ready(function() {
// validate the comment form when it is submitted
$("#Form").validate({
rules: {
"question1[]": "required"
},
messages: {
"question1[]": "Input is required",
}
});
});
But it goes on to the next fieldset with no error.
In this case, create a new input that's disabled, and when the individual weight values change, change the value of this disabled input to be the sum. Validate the disabled input - require it's value be equal to 10, and if it's not, show an error.

Categories

Resources