dcsimg

Bring Your Forms to Life With JavaScript

By Kris Hadlock

WEBINAR:
On-Demand

Building the Right Environment to Support AI, Machine Learning and Deep Learning


Tying the object to the form

The best part about creating an object like this is that tying it to the form that we created in listing 1 is straightforward, as is the method to tie it to any form in the future. The first thing to do is to import the JavaScript object along with the helper utils file (included in the source download), add ids to all elements so we can target them appropriately, then add an event to the field. In this case I choose onblur to make sure that the field had been completed by the user before validating. Within this event, simply add Validator.Validate(this) or Validator.Validate(this, "email") in order to validate an email or other custom element. In the body onload event, add the Initialize method and enter the appropriate ids, image paths and number of required fields as the parameters. Lastly, we add an onsubmit event to the form and make sure that all fields have been validated before allowing it to post. Listing 3 shows the new form incorporated with the Validator.

Note: If you didn't download the source code, the code below is the utils.js file.

Conclusion

Validating forms and preventing errors doesn't need to be a difficult task. With a little preparation you can create a reusable object and customize it later to enhance its power.

About the Author

Kris Hadlock is the owner and founder of Studio Sedition, a Web design and development firm. He is the author of Ajax for Web Application Developers and has been a feature writer for numerous Web sites and design magazines. To learn more about Kris, visit his Web site at www.studiosedition.com or his blog at blog.studiosedition.com




Page 3 of 3

Previous Page
1 2 3
 

Make a Comment

Loading Comments...

  • Web Development Newsletter Signup

    Invalid email
    You have successfuly registered to our newsletter.

    By submitting your information, you agree that htmlgoodies.com may send you HTMLGOODIES offers via email, phone and text message, as well as email offers about other products and services that HTMLGOODIES believes may be of interest to you. HTMLGOODIES will process your information in accordance with the Quinstreet Privacy Policy.

  •  
  •  
  •  
Thanks for your registration, follow us on our social networks to keep up-to-date