Solved

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

Posted on 2013-06-06
10
845 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
Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

 
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

DevOps Toolchain Recommendations

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

Question has a verified solution.

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

Any business that wants to seriously grow needs to keep the needs and desires of an international audience of their websites in mind. Making a website friendly to international users isn’t prohibitively expensive and can provide an incredible return…
Is your Office 365 signature not working the way you want it to? Are signature updates taking up too much of your time? Let's run through the most common problems that an IT administrator can encounter when dealing with Office 365 email signatures.
The viewer will the learn the benefit of plain text editors and code an HTML5 based template for use in further tutorials.
In this fourth video of the Xpdf series, we discuss and demonstrate the PDFinfo utility, which retrieves the contents of a PDF's Info Dictionary, as well as some other information, including the page count. We show how to isolate the page count in a…

778 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