Magento server side form validation

Zero Cool picture Zero Cool · Jul 29, 2011 · Viewed 14.7k times · Source

is there any server side form validation in magento? i have created a from and using magentos form validation but its not gonna work if someone disable the javascipt and enters something that can be harmful. if there is no built in class for that. could someone please point me in a direction how to implement a server side form validation as a backup. here is my my code for the form

<div style="border:0px solid red; margin:0px auto;">

<?php $_product = $this->getProduct(); ?>


<form id="test" action="<?php echo Mage::getUrl('pricenotify/pricenotify/db') ?>" method="post">

            <label for="price">Price *</label>
            <input type="text" id="price" name="price" value="" class="required-entry validate-number"/><br />
            <label for="email">Email Address *</label>
            <input type="text" id="email" name="email" value="" class="required-entry validate-email"/>
            <input type="hidden" id="id" name="id" value="<?php echo $_product->getId() ?>" />
            <input type="hidden" id="propri" name="propri" value="<?php echo $_product->getPrice() ?>" />

            <input type="submit" name="submit" value="<?php echo $this->__('Submit') ?>" onclick="if(customForm.validator && customForm.validator.validate()) this.form.request(); return false;" />

</form>

<script type="text/javascript">
//< ![CDATA[
var customForm = new VarienForm('test',false);
//]]>
</script>   

Answer

Renon Stewart picture Renon Stewart · Sep 24, 2012

If you want to keep it simple, you could do the validation in your controller

try {
            $postObject = new Varien_Object();
            $postObject->setData($post);

            $error = false;

            if (!Zend_Validate::is($postObject->getPrice(), 'NotEmpty')) {
                $error = true;
            }

            if (!Zend_Validate::is($postObject->getEmail(), 'EmailAddress')) {
                $error = true;
            }

            if ($error) {
                throw new Exception();
            }


            //save to db

            return;
        } catch (Exception $e) {
            Mage::getSingleton('customer/session')->addError(Mage::helper('pricenotify')->__('Unable to submit your request. Please, try again later'));
            $this->_redirect('/');

            return;
        }

Zend_Validate : http://files.zend.com/help/Zend-Framework/zend.validate.html