JQuery Form Validation

If I have a form with two inputs, First_Name and Last_name.  The First_Name is not required, BUT if the First_Name is filled in how do I make Last_Name required?
LVL 7
rgranlundAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

leakim971PluritechnicianCommented:
Test page : http://jsfiddle.net/rc031gn4/
(be careful with the case)
jQuery(function($) {
    $("form").submit(function(event) {
        var First_Name_not_blank = !!$.trim($("#First_Name").val())
        var Last_name_blank = !$.trim($("#Last_name").val())
        if(First_Name_not_blank && Last_name_blank) {
            alert("please fill last name too");
            event.preventDefault();
        }
    });
});

Open in new window

0
J NUnicorn wranglerCommented:
try using parsley

http://parsleyjs.org/

its is quite robust and saves you having to write your own code
0
J NUnicorn wranglerCommented:
0
Cloud Class® Course: C++ 11 Fundamentals

This course will introduce you to C++ 11 and teach you about syntax fundamentals.

rgranlundAuthor Commented:
@leakim  Is there a way to add a message to a div instead of an alert?
0
J NUnicorn wranglerCommented:
$("#div_id).html('data');
0
rgranlundAuthor Commented:
@Nagy can you elaborate just a little further?
0
J NUnicorn wranglerCommented:
this is assuming you are using jquery

if you would like to replace the content in a div to show a warning or success you can do something like the folllowing

<form name="form" id="form">
  <input ... />
  <input .../>
</form>
<div id="error_warning"></div>

Open in new window


1) we can place the div "error_warning" where ever we want it to be
2) we can style the div however we want

i cannot verify the above function to determine whether or not it work so lets assume it does

 
$("#form").on("submit" , function(event) {
        var First_Name_not_blank = !!$.trim($("#First_Name").val())
        var Last_name_blank = !$.trim($("#Last_name").val())
        if(First_Name_not_blank && Last_name_blank) {
            //ADJUST THE CONTENT TO BEHAVE AS YOU DESIRE
           $('#error_warning').html('you have to fill in the last name too'); //--> replaces the inner html content of the error div

            //STOPS THE DEFAULT ACTIONS OF A FORM SUBMIT
            event.preventDefault();
        }
    });
});

Open in new window

0
J NUnicorn wranglerCommented:
Again i suggest using a pre made library. it will save you time and it comes ready to implement you have the ability to validate in a variety of different ways and it is a lot easier. plus a lot of them are free

i use
http://parsleyjs.org/
0
leakim971PluritechnicianCommented:
0
RobOwner (Aidellio)Commented:
Using the validation plugin: http://jqueryvalidation.org/validate

http://jsbin.com/supet/1/edit

$(function() {
	$('#myform').validate({
		rules: {
			lastName: {
				required: function() { return ($('#firstName').val().length > 0) }
			}
		},
		messages: {
			lastName: "Please enter your lastname"
		}
	});
});

Open in new window


<form action="" id="myform">
			<label for="firstName">First Name:
				<input type="text" name="firstName" id="firstName"/>
			</label>
			<label for="">Last Name:
				<input type="text" name="lastName" id="lastName"/>
			</label>
			<button type='submit'>Submit</button>
		</form>

Open in new window

0
rgranlundAuthor Commented:
Does the form have to use an ID?  I have adjusted the script to show my real values, as per my form.
$(function() {
	$('.cart').validate({
		rules: {
			addon-28-bicycle-info[value-of-accesories]: {
              required: function() { return ($('.addon-28-bicycle-info[value-of-accesories]').val().length > 0) }
			}
		},
		messages: {
          addon-28-bicycle-info[value-of-accesories]: "Please the attached accesories."
		}
	});
});

Open in new window

0
RobOwner (Aidellio)Commented:
It makes sense to use an ID as you're targeting a specific element. If you can't change it and have to use a class then so be it.
Is your latest code not working?
0
rgranlundAuthor Commented:
This is closer to what I need but I would like the message to go into the Textarea and only print out once.  Right now, if I hit the submit button more than once it will re-print the message.:

<input type="text" id="valueOfAccesories"/>
<textarea id="attachedAccesories"></textarea>



<script type="text/javascript">
jQuery( document ).ready(function( $ ){

	$('#spokeCheckout').validate({
		errorElement: 'div',
		rules: {
			attachedAccesories: {
              required: function() { return ($('#valueOfAaccesories').val().length > 0)}
			}
		},
		messages: {
          attachedAccesories: "Please list the attached accessories."
		},
		submitHandler: function(form) {
		form.submit();
		}
	});
});
</script>

Open in new window

0
RobOwner (Aidellio)Commented:
I don't follow... Your logic above indicates that if someone enters something in the textbox then they also need to type into the textarea... If you want the error message to go into the message box doesn't that defeat the purpose?

The message only shows once here: http://jsbin.com/nehocu/1/edit
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
rgranlundAuthor Commented:
@rob, ok, that makes sense.  I was not thinking it all the through.  The following is what I have cause I am using Wordpress.

jQuery( document ).ready(function( $ ){

	$('#spokeCheckout').validate({
		errorElement: 'div',
		rules: {
			attachedAccesories: {
              required: function() { return ($('#valueOfAccesories').val().length > 0)}
			}
		},
		messages: {
          attachedAccesories: "Please list the attached accesories."
		},
		submitHandler: function(form) {
		form.submit();
		}
	});
});

Open in new window

0
RobOwner (Aidellio)Commented:
That code looks fine but it's showing the error message twice?
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
jQuery

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.