943,915 Members | Top Members by Rank

Ad:
Aug 8th, 2008
0

Required field validation

Expand Post »
I have an html form with multiple fields. Some of the fields are required, others are not. I have a JavaScript validation form that will send an alert if a field is empty. However, I only want it to send an alert if a required field is empty. How do I signify which fields in the form should cause the alert message to pop up?

Thanks,

Tom Tolleson
Similar Threads
Reputation Points: 10
Solved Threads: 0
Light Poster
Tom Tolleson is offline Offline
39 posts
since Oct 2007
Aug 9th, 2008
0

Re: Required field validation

You can test the field by className in your javascript and give all required fields the same class name.

Something like this
JavaScript / DHTML / AJAX Syntax (Toggle Plain Text)
  1. var form = document.getElementById('myform');
  2.  
  3. for ( var i = 0; i < form.length; i ++ ) {
  4. if ( /required/.test( form[i].className ) {
  5. if ( !form[i].value ) { // might have to tweek this some ...
  6. alert( 'You missed a required field: ' + field.name );
  7. return false; // test failed, abort form submit
  8. }
  9. }
  10. }
  11.  
  12. // all fields passed the test ...
  13. return true; // or maybe use
  14. form.submit();

What a required field might look like
JavaScript / DHTML / AJAX Syntax (Toggle Plain Text)
  1. <input type="text class="required" name="First Name" />
  2.  

This is off the top of my head, so I don't know it will work "out of the box" but it's the general idea anyway.

Hope this helps
Last edited by langsor; Aug 9th, 2008 at 3:40 am.
Reputation Points: 30
Solved Threads: 36
Posting Whiz
langsor is offline Offline
389 posts
since Aug 2008
Aug 14th, 2008
0

Re: Required field validation

Yes it did. Thanks!
Reputation Points: 10
Solved Threads: 0
Light Poster
Tom Tolleson is offline Offline
39 posts
since Oct 2007

This thread is solved

Either the thread starter or a moderator has marked this thread as solved. You can most likely trust the responses and answers given. There is most likely no reason for any further responses to be posted here. If you have a related question, please start a new thread in this forum instead.

This thread is more than three months old

No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.
Message:
Previous Thread in JavaScript / DHTML / AJAX Forum Timeline: why won't this script work?
Next Thread in JavaScript / DHTML / AJAX Forum Timeline: Are JavaScript namespaces a bad thing?





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC