Solved

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

Posted on 2013-06-06
10
821 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
Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 

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

6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

Join & Write a Comment

Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
This article discusses four methods for overlaying images in a container on a web page
This video teaches users how to migrate an existing Wordpress website to a new domain.
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

762 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

20 Experts available now in Live!

Get 1:1 Help Now