Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

Optional Form Fields - One field needs to be required and valid

Posted on 2013-06-06
10
Medium Priority
?
884 Views
Last Modified: 2013-06-16
Hi,

Im using jquery and jquery.validate to validate an online form i have made.
The client has requested that either the 'Home/Work' or 'Mobile' phone field has to be entered for the form to be valid. So both fields will be marked as a requirement to start with and the form becomes valid upon one of the fields being entered and valid, making the other field optional.

I hope that makes sense. Can someone please help with this one?

Please see below for my current HTML and JS.

<div class="user_bf_input">
<label for="cn_home">*Contact Number (Home/Work):</label>
<input name="cn_home" type="text" id="cn_home" size="15" />
</div>

<div class="user_bf_input">
<label for="cn_mobile">*Contact Number (Mobile):</label>
<input name="cn_mobile" type="text" id="cn_mobile" size="15" />
</div>

Open in new window


$(document).ready(function() {
&#9;$("#online_booking_form").validate({
&#9;&#9;rules: {
&#9;&#9;&#9;cn_home: {required: true, digits: true, minlength: 8},
&#9;&#9;&#9;cn_mobile: {required: true, digits: true, minlength: 10},
&#9;&#9;}
&#9;});
});

Open in new window

0
Comment
Question by:JiveMedia
  • 4
  • 4
8 Comments
 
LVL 15

Accepted Solution

by:
Jagadishwor Dulal earned 1000 total points
ID: 39227778
Change your script to group like:

<script>
$(document).ready(function() {
	  $('#online_booking_form').validate({ // initialize the plugin
        groups: {
            names: "cn_home cn_mobile"
        },
        rules: {
            cn_home: {
                require_from_group: [1, ".validateit"]
            },
            cn_mobile: {
                require_from_group: [1, ".validateit"]
            }
        },
        submitHandler: function (form) { // for demo
            alert('valid form submitted'); // for demo
            return false; // for demo
        }
    });

    jQuery.extend(jQuery.validator.messages, {
        require_from_group: jQuery.format("'Please enter either Home/Work or Mobile No fields.")
    });
});
</script>

Open in new window


Add Class to your input fields validateit like:

<div class="user_bf_input">
<label for="cn_home">*Contact Number (Home/Work):</label>
<input name="cn_home" type="text" id="cn_home" class="validateit" size="15" />
</div>

<div class="user_bf_input">
<label for="cn_mobile">*Contact Number (Mobile):</label>
<input name="cn_mobile" type="text" id="cn_mobile" size="15" class="validateit" />

Open in new window

0
 
LVL 15

Expert Comment

by:Jagadishwor Dulal
ID: 39227788
0
 

Author Comment

by:JiveMedia
ID: 39227833
Hi, I tried applying this to my code and it doesn't seem to be validating anything at all now, the form just submits. I have other rules for the form, will this make any difference in how it runs?

I would also like for the home and mobile phone fields to have min length and to be only digits too.

Please see below.

$(document).ready(function() {
$("#online_booking_form").validate({
		rules: {
			fname: {required: true, minlength: 3},
			lname: {required: true, minlength: 3},
			postcode: {required: true, minlength: 4},
			cn_home: {required: true, digits: true, minlength: 8},
			cn_mobile: {required: true, digits: true, minlength: 10},
			dob: "required",
			payment_method: "required",
			cc_type: "required",
			cc_number: {required: true, digits: true, minlength: 16, maxlength: 16},
			cvc_number: "required",
			other_source: "required",
			terms_of_booking: "required"
		}
	});
});

Open in new window

0
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
LVL 15

Expert Comment

by:Jagadishwor Dulal
ID: 39227842
Do you caheck jsfiddle or can you post your url?
0
 

Author Comment

by:JiveMedia
ID: 39227874
http://nationwidetraining.com.au/courses/transport-logistics/forklift-training/2-day-fork-lift-beginners/?eID=750

Click book now then try just submitting the form, the validation doesn't work anymore on the fields. The form just submits where as before the user was prompt to enter fields in.

I have the javascript in a seperate js file called booking-form.js if you look through a web inspector.
0
 

Author Comment

by:JiveMedia
ID: 39227886
Ok, got it working, needed to include the file additional-methods.min.js

Only thing now, is that the other rules have stopped working.
cn_home and cn_mobile work but fname and lname don't!

Any chance you could update the jsfiddle with an example with other fields for name etc that need a required state with min character amount!

Many thanks!
0
 
LVL 15

Expert Comment

by:Jagadishwor Dulal
ID: 39228368
I don't found your function for validation can you post here.
0
 

Author Comment

by:JiveMedia
ID: 39228910
HTML like below for form fields.
<div class="user_bf_input">
    <label for="fname">*First Name:</label>
    <input name="fname" type="text" id="fname" size="20" />
</div>
<div class="user_bf_input">
    <label for="lname">*Last Name:</label>
    <input name="lname" type="text" id="lname" size="20" />
</div>

Open in new window


$(document).ready(function () {

    $("#online_booking_form").validate({
        groups: {
            names: "cn_home cn_mobile"
        },
        rules: {
            fname: {
                required: true,
                minlength: 3
            },
            lname: {
                required: true,
                minlength: 3
            },
            postcode: {
                required: true,
                minlength: 4
            },
            cn_home: {
                require_from_group: [1, ".validateit"]
            },
            cn_mobile: {
                require_from_group: [1, ".validateit"]
            },
            dob: "required",
            payment_method: "required",
            cc_type: "required",
            cc_number: {
                required: true,
                digits: true,
                minlength: 16,
                maxlength: 16
            },
            cvc_number: "required",
            other_source: "required",
            terms_of_booking: "required"
        }
    });
    jQuery.extend(jQuery.validator.messages, {
        require_from_group: jQuery.format("'Please enter either Home/Work or Mobile No fields.")
    });
});

Open in new window

0

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Australian government abolished Visa 457 earlier this April and this article describes how this decision might affect Australian IT scene and IT experts.
In this blog, we’ll look at how improvements to Percona XtraDB Cluster improved IST performance.
The viewer will learn the benefit of using external CSS files and the relationship between class and ID selectors. Create your external css file by saving it as style.css then set up your style tags: (CODE) Reference the nav tag and set your prop…
In this fifth video of the Xpdf series, we discuss and demonstrate the PDFdetach utility, which is able to list and, more importantly, extract attachments that are embedded in PDF files. It does this via a command line interface, making it suitable …
Suggested Courses

876 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question