• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 169
  • Last Modified:

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?
0
rgranlund
Asked:
rgranlund
  • 5
  • 5
  • 4
  • +1
1 Solution
 
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
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

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

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 5
  • 5
  • 4
  • +1
Tackle projects and never again get stuck behind a technical roadblock.
Join Now