Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

JQuery Form Validation

Posted on 2014-03-20
12
Medium Priority
?
394 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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 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
Build and deliver software with DevOps

A digital transformation requires faster time to market, shorter software development lifecycles, and the ability to adapt rapidly to changing customer demands. DevOps provides the solution.

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

Hire Technology Freelancers with Gigs

Work with freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely, and get projects done right.

Question has a verified solution.

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

Introduction This article is intended for those who are new to PHP error handling (https://www.experts-exchange.com/articles/11769/And-by-the-way-I-am-New-to-PHP.html).  It addresses one of the most common problems that plague beginning PHP develop…
Today, the web development industry is booming, and many people consider it to be their vocation. The question you may be asking yourself is – how do I become a web developer?
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…
The viewer will learn how to dynamically set the form action using jQuery.

715 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