Solved

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

Posted on 2013-06-06
10
833 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
10 Comments
 
LVL 15

Accepted Solution

by:
Jagadishwor Dulal earned 500 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
 
LVL 15

Expert Comment

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

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

 

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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Building a website can seem like a daunting task to the uninitiated but it really only requires knowledge of two basic languages: HTML and CSS.
I've been asked to discuss some of the UX activities that I'm using with my team. Here I will share some details about how we approach UX projects.
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…
HTML5 has deprecated a few of the older ways of showing media as well as offering up a new way to create games and animations. Audio, video, and canvas are just a few of the adjustments made between XHTML and HTML5. As we learned in our last micr…

919 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

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now