Home Magento Customization

Out of the box Form Validation in Magento

16 September 2009 No Comment

Out of the box Form Validation in Magento

One of the coolest things in Magento is a form validation, and the way how it’s done. Magento uses Prototype library (which, personlay, I’m not a big fan of) to manage form validation. All you need to do when writing custom form is to assign a valid class names to your input fields. Here is an example of how your custom form might look in order to get use of automatic form validation.

<form name="<em><strong>my-custom-form</strong>" id="my-custom-form" action="" method="post">

<label for="firstname">< ?php echo $this->__('First name') ?> <span>*</span></label>
<input id="firstname" name="firstname" />

<label for="lastname">< ?php echo $this->__('Last name') ?> <span>*</span></label>
<input id="lastname" name="lastname" />

<label for="useremail">< ?php echo $this->__('Email') ?> <span>*</span></label>
<input type="text" name="useremail" id="useremail" />

<input type="submit" name="submit" value="<?php echo $this-/>__('Submit') ?>" />

</form>< ?php /* END OF my-custom-form */?>

<script type="text/javascript">
//< ![CDATA[
var customForm = new VarienForm('<em><strong>my-custom-form</strong>');
//]]>
</script>

You will notice all of the input fields have one common class name, required-entry. I’m not gonna go over all of the available class names here. To find available class names, try going to One page checkout page, where you have checkout form, then simply view source and look for class names next to input, radio select and other fields.

Most important thing besides assigning class names is that little piece of JavaScript below the form. Remember to pass form id into the new VarienForm object.

Basically thats it. Constructing the form this way, automaticaly makes your form reuse already existing validation code, the one that the rest of the shop is using.

By Branko Ajzele from Inchoo.net

Related posts:

  1. Contact Form in Magento
  2. Move mini-cart in the sidebar to the header (or anywhere) in Magento
  3. Advanced search in Magento and how to use it in your own way
  4. Add Adwords tracking code to order confirmation page in Magento
  5. Magento Vertical Category Menu

Leave your response!

Add your comment below, or trackback from your own site. You can also subscribe to these comments via RSS.

Be nice. Keep it clean. Stay on topic. No spam.

You can use these tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Spam Protection by WP-SpamFree

Security Code: