Out of the box Form Validation in Magento

Form Validation in Magento

Magento uses Prototype library to manage form validation. This comes in handy, because all you need to do when writing custom form is to assign a valid class names to your input fields, and pass the form id to VarienForm object.

Let’s look at this example of validation in Magento.

<form name="test-form" id="my-custom-form" action="" method="post">
    <label for="firstname"><?php echo $this->__('First name') ?> <span class="required">*</span></label><br />
    <input id="firstname" name="firstname" class="input-text required-entry" />
    <label for="lastname"><?php echo $this->__('Last name') ?> <span class="required">*</span></label><br />
    <input id="lastname" name="lastname" class="input-text required-entry" />
    <label for="useremail"><?php echo $this->__('Email') ?> <span class="required">*</span></label><br />
    <input type="text" name="useremail" id="useremail" class="input-text required-entry validate-email" />
    <input type="submit" name="submit" value="<?php echo $this-/>__('Submit') ?>" />
</form>
<script type="text/javascript">
    //< ![CDATA[
        var customForm = new VarienForm('my-custom-form');
    //]]>
</script>

I also took some time to extract all validation rules you can use, and their error message. You can find the methods yourself by looking in js/prototype/validation.js on line 414

'validate-no-html-tags'         => 'HTML tags are not allowed'
'validate-select'               => 'Please select an option.'
'required-entry'                => 'This is a required field.'
'validate-number'               => 'Please enter a valid number in this field.'
'validate-number-range'         => 'The value is not within the specified range.'
'validate-digits'               => 'Please use numbers only in this field. Please avoid spaces or other characters such as dots or commas.'
'validate-digits-range'         => 'The value is not within the specified range.'
'validate-alpha'                => 'Please use letters only (a-z or A-Z) in this field.'
'validate-code'                 => 'Please use only letters (a-z), numbers (0-9) or underscore(_) in this field, first character should be a letter.'
'validate-alphanum'             => 'Please use only letters (a-z or A-Z) or numbers (0-9) only in this field. No spaces or other characters are allowed.'
'validate-alphanum-with-spaces' => 'Please use only letters (a-z or A-Z), numbers (0-9) or spaces only in this field.'
'validate-street'               => 'Please use only letters (a-z or A-Z) or numbers (0-9) or spaces and # only in this field.'
'validate-phoneStrict'          => 'Please enter a valid phone number. For example (123) 456-7890 or 123-456-7890.'
'validate-phoneLax'             => 'Please enter a valid phone number. For example (123) 456-7890 or 123-456-7890.'
'validate-fax'                  => 'Please enter a valid fax number. For example (123) 456-7890 or 123-456-7890.'
'validate-date'                 => 'Please enter a valid date.'
'validate-date-range'           => 'The From Date value should be less than or equal to the To Date value.'
'validate-email'                => 'Please enter a valid email address. For example johndoe@domain.com.'
'validate-emailSender'          => 'Please use only visible characters and spaces.'
'validate-password'             => 'Please enter 6 or more characters. Leading or trailing spaces will be ignored.'
'validate-admin-password'       => 'Please enter 7 or more characters. Password should contain both numeric and alphabetic characters.'
'validate-both-passwords'       => 'Please make sure your passwords match.'
'validate-url'                  => 'Please enter a valid URL. Protocol is required (http://, https:// or ftp://)'
'validate-clean-url'            => 'Please enter a valid URL. For example http://www.example.com or www.example.com'
'validate-identifier'           => 'Please enter a valid URL Key. For example "example-page", "example-page.html" or "anotherlevel/example-page".'
'validate-xml-identifier'       => 'Please enter a valid XML-identifier. For example something_1, block5, id-4.'
'validate-ssn'                  => 'Please enter a valid social security number. For example 123-45-6789.'
'validate-zip'                  => 'Please enter a valid zip code. For example 90602 or 90602-1234.'
'validate-zip-international'    => 'Please enter a valid zip code.'
'validate-date-au'              => 'Please use this date format: dd/mm/yyyy. For example 17/03/2006 for the 17th of March, 2006.'
'validate-currency-dollar'      => 'Please enter a valid $ amount. For example $100.00.'
'validate-one-required'         => 'Please select one of the above options.'
'validate-one-required-by-name' => 'Please select one of the options.'
'validate-not-negative-number'  => 'Please enter a number 0 or greater in this field.'
'validate-zero-or-greater'      => 'Please enter a number 0 or greater in this field.'
'validate-greater-than-zero'    => 'Please enter a number greater than 0 in this field.'
'validate-state'                => 'Please select State/Province.'
'validate-new-password'         => 'Please enter 6 or more characters. Leading or trailing spaces will be ignored.'
'validate-cc-number'            => 'Please enter a valid credit card number.'
'validate-cc-type'              => 'Credit card number does not match credit card type.'
'validate-cc-type-select'       => 'Card type does not match credit card number.'
'validate-cc-exp'               => 'Incorrect credit card expiration date.'
'validate-cc-cvn'               => 'Please enter a valid credit card verification number.'
'validate-ajax'                 => ''
'validate-data'                 => 'Please use only letters (a-z or A-Z), numbers (0-9) or underscore(_) in this field, first character should be a letter.'
'validate-css-length'           => 'Please input a valid CSS-length. For example 100px or 77pt or 20em or .5ex or 50%.'
'validate-length'               => 'Text length does not satisfy specified text range.'
'validate-percents'             => 'Please enter a number lower than 100.'
'validate-cc-ukss'              => 'Please enter issue number or start date for switch/solo card type.'

In case you would want to add your custom validation rule, just create a javascript file with any name you want in js folder of your Magento installation. I’ll show you how to do this in the following example.

Say you want to modify one of the validation rules, the best way would be to create a method with a same name and load it after the original method. This way, all calls would be redirected to your method instead of the original. Just be careful if you’re overriding validation rules like this, because javascript is only client-side validation. Your may have your server validate the field as well – which can cause some errors even though the value in field was entered the way you wanted.
So, be sure to test your validation rule.

For our purposes, we’ll override Magento’s validate-email method. We want it to accept only email addresses ending with @gmail.com.

Let’s create our javascript file and place it in the js folder.

js/inchoo.js

Validation.add('validate-email', 'Please enter a valid Gmail address. For example johndoe@gmail.com.', function(v) {
    return Validation.get('IsEmpty').test(v) || /^([a-zA-Z0-9]+[a-zA-Z0-9._%-]*@gmail\.com)$/i.test(v)
})

All we need to do now is include our validation script. We’ll do that using Magento’s addJs method which will add the javascript file to our website’s head.

<default>
    <reference name="head">
        <action method="addJs"><script>inchoo.js</script></action>
    </reference>
</default>

You can do this from any layout file (preferably your module’s layout file), Magento did it in their theme’s layout page called page.xml located in app/design/frontend/base/default/layout/page.xml

Hope this clears some things up for you. At the very least, you now have a list of all validation classes in Magento.

Note: This is a revamp of an article originally written in January 2009.

If you’re having questions or need help regarding Magento development, we would be happy to help you out by creating a detailed custom report based on our technical audit. Feel free to get in touch!

Related Inchoo Services

You made it all the way down here so you must have enjoyed this post! You may also like:

How To Connect Google Analytics 4 To Magento 2 Bojan Mareljic
Bojan Mareljic, | 36

How To Connect Google Analytics 4 To Magento 2

Magento form field AJAX validation Branko Ajzele
Branko Ajzele, | 8

Magento form field AJAX validation

Contact Form in Magento Domagoj Potkoc
Domagoj Potkoc, | 114

Contact Form in Magento

24 comments

  1. This is a good method, however it will set the validation on Client side only which could be easily broken. What about adding validation on server side in Zend Validator, can you provide details ?

  2. To check if a validation class is registered, just check with Validation.methods

    Example:
    if ( ! Validation.methods[ ‘my-custom-validation-class’ ] ) { // validation class not registered }

  3. The first letter of the constructor function “VarienForm” should be lowercase, if you are validating forms in the adminhtml, in the admin interface.
    var customForm = new varienForm(‘my-custom-form’);

  4. How can we change the telephone format like this 306.789.9876 in the checkout form? Please I need step by step instruction.

  5. I got error ‘VarienForm not define’ in magento 1.7 admin panel when i use same code as below.

    1. I got same error on magento 1.9.2. I tried to add the varien/form.js file by this code:

      varien\form.js

      but it didnt work 🙁

  6. Hi,
    is there a way to add validation for a unique field? Say I have two input fields for emails (primary email and secondary email) and I have these 2 inputs to have different value, so if user enters the same email both for primary and secondary email, the validation should fail.. how can I achieve this?

    Thanks

  7. Hi i have done below format

    HTML code

    <input type="text" name="telephone" id="telephone" value="htmlEscape($this->getFormData()->getTelephone()) ?>” title=”__(‘Telephone’) ?>” class=”input-text validate-numeric-contact” />

    js Code add below in billing.phtml

    // 0){
    if(v.length !=10){
    return false;
    }else if(v[0] != 9 || v[1] != 1 ){

    //return false;
    }else if(v[2]!=9 && v[2]!=8 && v[2]!=7){

    return false;
    }

    return true;

    }else {
    return false;
    }

    }
    ]])};
    var dataForm = new VarienForm(‘form-id’, true);

    //]]>

  8. Hey, thanks for the info, but inspite of removing client-side validation of email address, I still receive ’email’ is not a valid email address on entering email address without ‘@’ and .com

  9. Thank for the tuto, one question how can i translate the message from the validation Js file

  10. So this is all taking it from the client side. What about server side validation? With all due respect, I can bypass JavaScript VERY easily if I wanted to be malicious. Where in the Mage model is the server side definition of validation requirements stored? Thanks!

  11. I insert multiple form in one page, each one with unic id, but validator works only on one form.
    Did you know why?
    I can apply validation individually in two forms on one page?
    Thank you so much.

  12. Great Article!!
    I’ve a problem in a custom validation: I want to change the rules of validation-zip-international, i want to check if the inputs are only number and that the lenght of the string must be 5
    i wrote this code
    Validation.add(‘validate-zip-international’, ‘Inserisci un CAP corretto, 5 numeri.’, function(v) {
    return Validation.get(‘IsEmpty’).test(v) || !/[^\d{5}]/.test(v);
    })
    If I test the regular expression ^\d{5,5} works, but magento doesn’t validate the length of the string.

    Thanks!

  13. Hi dear, I see more magento examples, but I need another example.

    I need get the value from the tag text field value, for a new custom validation in orden module

    I need this, form example , how get the value (lalal) into a php variable, $variable = lalalal …

    I need to get a id customer number from the order module to validate..

    You know how make this?

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <blockquote cite=""> <code> <del datetime=""> <em> <s> <strike> <strong>. You may use following syntax for source code: <pre><code>$current = "Inchoo";</code></pre>.

Tell us about your project

Drop us a line. We'd love to know more about your project.