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

JQuery Form Validation

I'm not really sure how to writ a JQuery Validation script.
I have a form that needs to be validated ONLY in one field is filled in.  For example, if someone fills in the first name, they MUST fill in a last name.  BUT if they do not fill in the first name, they do not need to fill in the last name.

Can anyone help me out and/or point me to a good tutorial?
<script>
$(document).ready(function() {
	$('input[type="submit"]').click(function() {
		if ($(this).attr("name") == "first_name" isset && .attr("name") == "last_name" is empty {
			alert "You must fill in the last name;"
		
		}
	});
});
</script>

<form id="name" method="POST">
	<input type="text" name="first_name"/>
	<input type="text" name="last_name"/>
	<span class="alert" style="display:none;">You Must Fill In A Last Name!</span>
	<input type="submit" name="submit" value="SUBMIT"/>	
</form>

Open in new window

0
rgranlund
Asked:
rgranlund
  • 5
  • 4
  • 2
  • +1
1 Solution
 
Ray PaseurCommented:
This seems to be the one that gets the most traction.  You can fork it on GitHub or just download a copy for your own use.
https://plugins.jquery.com/validation/

Documentation here:
http://jqueryvalidation.org/documentation
0
 
Big MontySenior Web Developer / CEO of ExchangeTree.org Commented:
first, assign IDs to your fields, it'll make your life so much easier :)

if you don't want to use the jquery validator, then you could do something like the following:

<script>
$(document).ready(function() {
	$('input[type="submit"]').click(function() {
		if( $('#first_name').val() != '' && $('#last_name').val() == '' )  
			alert "You must fill in the last name;"
	});
});
</script>

<form id="name" method="POST">
	<input type="text" name="first_name" id="first_name"/>
	<input type="text" name="last_name" id="last_name"/>
	<span class="alert" style="display:none;">You Must Fill In A Last Name!</span>
	<input type="submit" name="submit" value="SUBMIT"/>	
</form>

Open in new window

0
 
leakim971PluritechnicianCommented:
Test page : http://jsfiddle.net/aV3q3/

$(document).ready(function() {

    $('form').submit(function(event) {
        var numberOfFieldWithName = $(":text[name]");
        var errors_length = 0;
        numberOfFieldWithName.each(function(i, field) {
            if($(this).val()=="") {
                errors_length++;
                $(this).next("span").show();
            }
            else {
                $(this).next("span").hide();
            }
        });
        if(errors_length>0) {
            event.preventDefault();
        }
   });

});

Open in new window

0
Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

 
rgranlundAuthor Commented:
@BigMontey

At a glance, do you have any idea why the following does not work?  When I click submit, the submission form goes through even though the criteria has not been met.
0
 
rgranlundAuthor Commented:
Sorry, the code will help

$('form').submit(function(event) {
        var numberOfFieldWithName = $(":text[name]");
        var errors_length = 0;
        numberOfFieldWithName.each(function(i, field) {
            if( $('#color_picker').val() != '' && $('#color-picker-comment').val() == '' ) {
                errors_length++;
                $(this).next("span").show();
            }
            else {
                $(this).next("span").hide();
            }
        });
        if(errors_length>0) {
            event.preventDefault();
        }
	});

Open in new window

0
 
Big MontySenior Web Developer / CEO of ExchangeTree.org Commented:
if you added IDs to the fields, then you don't need this line and it's ending curly braces:

numberOfFieldWithName.each(function(i, field) {
0
 
rgranlundAuthor Commented:
I think I may have mislead you just a little bit.  In my form there is a radio button and a text box.  Not 2 text boxes. Also, should I add the form ID to the JQuery?
$('form').submit(function(event) {
        var numberOfFieldWithName = $(":text[name]");
        var errors_length = 0;
            if( $('#color_picker').val() != '' && $('#color-picker-comment').val() == '' ) {
                errors_length++;
                $(this).next("span").show();
            }
            else {
                $(this).next("span").hide();
            }
        if(errors_length>0) {
            event.preventDefault();
        }
	});

<form id="name" method="POST">
	<input type="text" name="color_picker" id="color_picker" value="yes"/>YES
        <input type="text" name="color_picker" id="color_picker" value="no"/>NO
	<input type="text" name="color-picker-comment" id="color-picker-comment"/>
	<span class="alert" style="display:none;">You Must Fill In A Description!</span>
	<input type="submit" name="submit" value="SUBMIT"/>	
</form>

Open in new window

0
 
Big MontySenior Web Developer / CEO of ExchangeTree.org Commented:
uhhh ya, in the future, please just ask what you need to do. usually when you try to simplify things, it tends to get more complicated :)

try this for code:

$('form').submit(function(event) {
        var numberOfFieldWithName = $(":text[name]");
        var errors_length = 0;
            if( ("#color_pickerYes").attr('checked', 'checked') && $('#color-picker-comment').val() == '' ) {
                errors_length++;
                $(this).next("span").show();
            }
            else {
                $(this).next("span").hide();
            }
        if(errors_length>0) {
            event.preventDefault();
        }
	});

<form id="name" method="POST">
	<input type="text" name="color_picker" id="color_pickerYes" value="yes"/>YES
        <input type="text" name="color_picker" id="color_pickerNo" value="no"/>NO
	<input type="text" name="color-picker-comment" id="color-picker-comment"/>
	<span class="alert" style="display:none;">You Must Fill In A Description!</span>
	<input type="submit" name="submit" value="SUBMIT"/>	
</form>

Open in new window


this should fire when the YES radio button is checked and the textbox is empty. Note the ID changes I made to the radio buttons, every element on your page must have an unique ID
0
 
rgranlundAuthor Commented:
How would you do it if you had multiple radio buttons?  Like the following. (I', just trying to better understand)

Could I do something like this?  

The reason I ask is what if I add more radio buttons and if one of them is checked, I want to make the description REQUIRED

	$('form').submit(function(event) {
        var numberOfFieldWithName = $(":text[name]");
        var errors_length = 0;
            if( ($(this).attr("name") == "color_picker").attr('checked', 'checked') && $('#color-picker-comment').val() == '' ) {
                errors_length++;
                $(this).next("span").show();
            }
            else {
                $(this).next("span").hide();
            }
        if(errors_length>0) {
            event.preventDefault();
        }
	});
<form id="name" method="POST"> 
      <input type="radio" name="color_picker" value="red"/>Red
      <input type="radio" name="color_picker" value=blue"/>Blue
      <input type="radio" name="color_picker" value="green"/>Green

	<input type="text" name="color-picker-comment" id="color-picker-comment"/>
	<span class="alert" style="display:none;">You Must Fill In A Description!</span>
	<input type="submit" name="submit" value="SUBMIT"/>	
</form>

Open in new window

0
 
Big MontySenior Web Developer / CEO of ExchangeTree.org Commented:
again, if you can get into the habit of using IDs on all of your form elements, you'll make your life so much easier. is there a particular reason you don't want to use IDs?

by using the IDs and the code I gave earlier, you can easily check the "checked" attribute of any given element, then do whatever you want.
0
 
Ray PaseurCommented:
Please take a moment to learn about "selectors" in HTML.  It's not completely intuitive, but it's absolutely required knowledge if you're going to have any success with client-side applications.  This should help you get an overview.

http://www.w3schools.com/css/css_id_class.asp

Selectors are used to attach style to elements of the HTML document.  They are used by JavaScript to locate and change components of the elements (value, style, HTML, etc).  So they are really one of the most important fundamental things about the document object model.  It's almost impossible to apply the principles of jQuery if you do not understand how it uses selectors.

http://api.jquery.com/category/selectors/

You might want to set up a few simple examples of id and class selectors for your own reference library.  Just a thought.
0
 
rgranlundAuthor Commented:
Thank you for all of this helpful information.  I have a few final questions:
1. Does the line in the function ( var numberOfFieldWithName = $(":text[name]");) Refer to the ID of the Form?  If not which line does?
2. Does it matter if this function is in a function file that is called?
3. Does it matter if it is in the header or the footer?
4. Will it still work if an action is added to the form that leeds it away?

You can see my code here: http://jsfiddle.net/aV3q3/6/
maybe you can see what I am doing wrong?
0
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.

Join & Write a Comment

Featured Post

Cloud Class® Course: Python 3 Fundamentals

This course will teach participants about installing and configuring Python, syntax, importing, statements, types, strings, booleans, files, lists, tuples, comprehensions, functions, and classes.

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