Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

JQuery Form Validation

Posted on 2014-03-20
12
Medium Priority
?
396 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 111

Expert Comment

by:Ray Paseur
ID: 39943423
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 34

Expert Comment

by:Big Monty
ID: 39943557
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 83

Expert Comment

by:leakim971
ID: 39943601
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
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
LVL 7

Author Comment

by:rgranlund
ID: 39943729
@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
ID: 39943745
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 34

Expert Comment

by:Big Monty
ID: 39943753
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
 
LVL 7

Author Comment

by:rgranlund
ID: 39943771
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 34

Accepted Solution

by:
Big Monty earned 2000 total points
ID: 39943833
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
ID: 39943886
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 34

Expert Comment

by:Big Monty
ID: 39944224
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 111

Expert Comment

by:Ray Paseur
ID: 39945418
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
ID: 39945738
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

Industry Leaders: 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!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Build an array called $myWeek which will hold the array elements Today, Yesterday and then builds up the rest of the week by the name of the day going back 1 week.   (CODE) (CODE) Then you just need to pass your date to the function. If i…
In this blog, we’ll look at how improvements to Percona XtraDB Cluster improved IST performance.
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)
Suggested Courses

885 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