Solved

JQuery Form Validation

Posted on 2014-03-20
12
373 Views
Last Modified: 2014-03-21
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
Comment
Question by:rgranlund
  • 5
  • 4
  • 2
  • +1
12 Comments
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
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
 
LVL 32

Expert Comment

by:Big Monty
Comment Utility
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
 
LVL 82

Expert Comment

by:leakim971
Comment Utility
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
 
LVL 7

Author Comment

by:rgranlund
Comment Utility
@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
 
LVL 7

Author Comment

by:rgranlund
Comment Utility
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
 
LVL 32

Expert Comment

by:Big Monty
Comment Utility
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
Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

 
LVL 7

Author Comment

by:rgranlund
Comment Utility
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
 
LVL 32

Accepted Solution

by:
Big Monty earned 500 total points
Comment Utility
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
 
LVL 7

Author Comment

by:rgranlund
Comment Utility
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
 
LVL 32

Expert Comment

by:Big Monty
Comment Utility
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
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
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
 
LVL 7

Author Comment

by:rgranlund
Comment Utility
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

Featured Post

Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

Join & Write a Comment

In this article you'll learn how to use Ajax calls within your CodeIgniter application. To explain this, I'll illustrate how to implement a simple contact form to allow visitors to send you an email through your web site.
Since pre-biblical times, humans have sought ways to keep secrets, and share the secrets selectively.  This article explores the ways PHP can be used to hide and encrypt information.
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)

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

6 Experts available now in Live!

Get 1:1 Help Now