Form Validation in Magento

      No Comments on Form Validation in Magento

I had an interesting challenge of dealing with magento quantities in decimals. The site needed to be able to allow for quantities of a min of .5 in increments of .25.  At first glance, it looked like allow decimals in admin combined with qty increments would work.  Well, the words made me think it would work, but it didn’t.  It allowed any qty to be entered, so someone could put in 1.35.  Not good.

After reading some documentation on magento 1.4.2.0, it mentioned validating qty increments.  I didn’t read the details, but wanted to upgrade it anyways, so 20min. and one upgrade later I had broken it more.  Turns out the validation that was fixed was in admin because decimal qty increments aren’t supported.

Ideally I would want to write an extension that supports what I was trying to create, but there’s not time for that now, so instead in comes Magento form validation.

It’s actually pretty simple to do form validation.  There’s a javascript file in prototype called validation.js that lists all the possible validation types.  To validate against a type, simple add that class to the form input and make sure that the form validates.

My case required me to add another validation type, but that was easy.  Here’s what I did:

In /js/prototype/validation.js around line 569, I added my own validation type.
[sourcecode language=”javascript”]
//Begin Validation Code added by Irish Titan for add to cart qty issues.
[‘validate-fabric-qty’, ‘Please enter a quantity in increments of .25 yards.’, function(v) {
v = parseNumber(v);
return (!isNaN(v) && v>=0 && v % .25 == 0);
}],
//End code added by Irish Titan
[/sourcecode]

Then I just added validate-fabric-qty to the class on the input fields that I needed that validation on.

Finally, there was a form that didn’t validate client side, so I added the varian form validate code to that page like this:
[sourcecode language=”javascript”]
var cartForm = new VarienForm(‘cartForm’);
cartForm.submit = function(){
if (this.validator.validate()) {
this.form.submit();
}
}.bind(cartForm);
[/sourcecode]

The same logic can be used for any magento form, or custom magento forms. Take a look at validation.js to see all the pre-built validation options.

Leave a Reply

Your email address will not be published. Required fields are marked *