Figuring out form validation to validate a value across multiple inputs - javascript

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.

Related

Multiple language validation handling logic

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,

Trying to validate form field with jQuery

I know I must be missing something super simple here, because in theory this code is supposed to work, but it's not, and I cannot understand why. I'm trying to work out my own jQuery form validation, because I tried the jQuery form validator plug-in, and while setting up the rules and messages is perfectly simple, figuring out how to get the error message to show up where I wanted it to was a nightmare (couldn't get the message to show up AFTER radio buttons, for example.)
I've got the 1st part of my attempted validation working, but I can't clear the message once you enter something in the field. Also, the message pops up even when conditions are met, which doesn't make sense to me.
here's the jsfiddle
html
<form>
<p>
<lable for="name">Enter your name:</lable>
<input type="text" id="name" name="name">
<span class="error"></span>
</p>
<lable for="age">Enter your Age:</lable>
<input type="text" id="age" name="age" width="3">
<span class="error"></span>
</p>
</form>
jQuery
$("input").focusin(function(){//highlight input field on focus
$(this).css("background-color", "yellow");
});
$("input").focusout(function(){
$(this).css("background-color", "white");
});
$("#name").keyup(function(){ //check against non-letter characters in name field
var notLetter = /[^A-Za-z]/;
if (notLetter.test($(this))){
$(this).next(".error").text("Letters only please!");
} else {
$(this).next(".error").text("");
}
});
$("#name").focusout(function(){//check that the field isn't empty
if ($(this).val() == ""){
$(this).next(".error").text("You forgot to enter your name!");
} else {
$(this).next(".error").text("");
}
});
$("#age").keyup(function(){//check against non-number characters in age
var notNumber = /[^0-9]/;
if (notNumber.test($(this)) != false){
$(this).next(".error").text("Numbers only please!");
} else {
$(this).next(".error").text("");
}
});
$("#age").focusout(function(){//check that the field isn't empty
if ($(this).val() == ""){
$(this).next(".error").text("You forgot to enter your name!");
} else {
$(this).next(".error").text("");
}
});
You forgot the $(this).val()
$("#name").keyup(function(){ //check against non-letter characters in name field
var notLetter = /[^A-Za-z]/;
if (notLetter.test($(this).val())){
$(this).next(".error").text("Letters only please!");
} else {
$(this).next(".error").text("");
}
});
and again at age
$("#age").keyup(function(){//check against non-number characters in age
var notNumber = /[^0-9]/;
if (notNumber.test($(this).val())){
$(this).next(".error").text("Numbers only please!");
} else {
$(this).next(".error").text("");
}
});
also you can remove != false - e.g
if (test != false)
is the same as
if (test)
Heres the fixed up fiddle
Need to Remember Some thing while validating form Using JS:-
Check input value Using (this).val();
if Error Occur then forward to next vale with Error .
Check test value is false or true using if (test != false) or if (test)
then forward your Control for success page
You can use the lettersonly rule.
Here's an example:
Define a variable validator and do this :
validator = $("form").validate({
rules: {
name: { required: true,
lettersonly: true
}
}
});
It's worth noting, each additional method is independent, you can include that specific one, just place this before your .validate() call:
jQuery.validator.addMethod("lettersonly", function(value, element) {
return this.optional(element) || /^[a-z]+$/i.test(value);
}, "Letters only please");
you need to call
$("form").valid()
and if it is valid means without any errors then do :
validator.hideErrors();
$("form" div.has-error").removeClass("has-error");
For age input for numeric only jQuery has implemented its own jQuery.isNumeric() added in v1.7. See: https://stackoverflow.com/a/20186188/66767

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"
},

Categories

Resources