Solved

JQuery Form Validation

Posted on 2014-03-20
12
385 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 109

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 33

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 82

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
The New “Normal” in Modern Enterprise Operations

DevOps for the modern enterprise offers many benefits — increased agility, productivity, and more, but digital transformation isn’t easy, especially if you’re not addressing the right issues. Register for the webinar to dive into the “new normal” for enterprise modern ops.

 
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 33

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 33

Accepted Solution

by:
Big Monty earned 500 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 33

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 109

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

Active Directory Webinar

We all know we need to protect and secure our privileges, but where to start? Join Experts Exchange and ManageEngine on Tuesday, April 11, 2017 10:00 AM PDT to learn how to track and secure privileged users in Active Directory.

Question has a verified solution.

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

Password hashing is better than message digests or encryption, and you should be using it instead of message digests or encryption.  Find out why and how in this article, which supplements the original article on PHP Client Registration, Login, Logo…
This article discusses how to create an extensible mechanism for linked drop downs.
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

830 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