Programming and Webmasters forum
HomeSearchRecent PostsLoginRegister Contact Us

Username  
Password
Announcing 14th Weekly Contest - From 25 July To 01 August.

Win every week on this forum.

Chek out How To Win?
 

Pages: [1]   Go Down
 
  Email this topic  |  Print
0 Members and 1 Guest are viewing this topic.

Improving my form validation

 
webmaster forum
giclee12  Offline
Contest Points: 100
 
New Coder
Posts: 10
Topics: 3
February 17, 2010, 03:19:48 AM

Hi all.

A JavaScript beginner looking for help to make form validation more user-friendly.

I found the following function on the web and modified it slightly for my form, and it works fine as far as it goes.

I have added class="REQUIRED" to the tag of form fields that are compulsory, and there's an e-mail field which has class="REQUIRED EMAIL".
My question is, how do I clearly indicate in the alert box the field that is being referred to? For example, can I add some otherwise harmless element to the tag of REQUIRED fields and have it printed out in the alert box? So the alert box would read something like "Please fill out this field: Contact Name".

Quote
<script>
function validateFields() {

  var elements = document. forms["form1"]. elements;
  var emailPattern = /^[\w\. \-]+@([\w\-]+\. )+[a-zA-Z]+$/;

  for (var i = 0; i < elements. length; i++)
  {
    if (/(^| )REQUIRED( |$)/. test(elements. className) && elements. value == "")
    {
      elements. focus();
      alert("Please fill out this field. ");
      return false;
    }

    if (/(^| )EMAIL( |$)/. test(elements. className) && !emailPattern. test(elements. value))
    {
      elements. focus();
      alert("Please provide a valid e-mail address. ");
      return false;
    }
  }
}

Retractable Reels | Anchor Hocking Glass
 
webmaster forum
Admin  Offline
*
 
Hacker
Location: India
Gender: Male
Posts: 1101
Topics: 94
Technical_Talk
WWW
February 17, 2010, 07:24:55 AM

Have you tried with elements.name?

You can append the element name into the alert message.

Watch out for the latest Weekly Contests | Contest Rules
A Game - Say "Hello"
We are looking for Global Moderator
 
webmaster forum
singam  Offline
Contest Points: 100
 
New Coder
Posts: 39
Topics: 15
June 23, 2010, 02:13:39 AM

If you're looking to validate user input (maybe a form or something) you might want to look at filter_var() and some of its friends.

hxxp: php. net/filter_var

It handles a lot of common cases and has some pretty nice features (enforced value ranges for integers, formatting, and so on).  If the built-in filter suite doesn't do what you want, you can define your own filter and pass it to filter_var() as a callback.



« Last Edit: June 24, 2010, 06:53:19 AM by Admin »
 
  Email this topic  |  Print
Pages: [1]   Go Up
 
Jump to:  



Powered by SMF 1.1.11 | SMF © 2006-2009, Simple Machines LLC


Google visited last this page July 29, 2010, 07:21:35 PM

Valid XHTML 1.0 Transitional     Valid XHTML 1.0 Transitional