Link to home
Start Free TrialLog in
Avatar of Robert Granlund
Robert GranlundFlag for United States of America

asked on

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?
Avatar of leakim971
leakim971
Flag of Guadeloupe image

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

Avatar of J N
J N

try using parsley

http://parsleyjs.org/

its is quite robust and saves you having to write your own code
Avatar of Robert Granlund

ASKER

@leakim  Is there a way to add a message to a div instead of an alert?
$("#div_id).html('data');
@Nagy can you elaborate just a little further?
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

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/
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

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

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?
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

ASKER CERTIFIED SOLUTION
Avatar of Rob
Rob
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
@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

That code looks fine but it's showing the error message twice?