How to add a custom validation to Magento prototype

14,437

Solution 1

You can create your own custom validation function using

<script type="text/javascript">
    var theForm = new VarienForm('theForm', true);
    Validation.add('validate-must-be-baz','You failed to enter baz!',function(the_field_value){
        if(the_field_value == 'baz')
        {
            return true;
        }
        return false;
    });

</script>

See http://magento-quickies.tumblr.com/post/6579512188/magento-custom-form-validation

or

if(Validation) {       
   Validation.addAllThese([     
    [
        'validation-myown',      
        'Please insert proper word',   
        function(v,r){ return v.indexOf('valid')==-1?false:true } 
    ],
   [ ]   
])
}

see http://blog.baobaz.com/en/blog/custom-javascript-form-validators

Solution 2

In /js/prototype/validation.js (or the files for this kind of thing you have). You have a section with an array of :

classname :message on fail : function(v){your check return true/false;} to check if v is valid or not

This section is around line 420.

You can add your validation to this array or modify validate-url here is what it looks like :

 ['validate-url', 'Please enter a valid URL. Protocol is required (http://, https:// or ftp://)', function (v) {
            v = (v || '').replace(/^\s+/, '').replace(/\s+$/, '');
            return Validation.get('IsEmpty').test(v) || /^(http|https|ftp):\/\/(([A-Z0-9]([A-Z0-9_-]*[A-Z0-9]|))(\.[A-Z0-9]([A-Z0-9_-]*[A-Z0-9]|))*)(:(\d+))?(\/[A-Z0-9~](([A-Z0-9_~-]|\.)*[A-Z0-9~]|))*\/?(.*)?$/i.test(v)
        }],

Edit : R.S answered maybe better by showing how to do without changing the js file. More convenient ;)

Share:
14,437
Vlad Preda
Author by

Vlad Preda

PHP programmer, Zend and Magento certified

Updated on August 05, 2022

Comments

  • Vlad Preda
    Vlad Preda almost 2 years

    I want to make a simple url validator for some custom fields. I tried the default ones (adding the class validate-url or validate-clean-url to the input) - but these don't work quite as I would like them to, so I want to write some of my own javascript, but integrated with the prototype validation.

    Does anyone have any ideas how I can do this?

    I didn't find anything helpful in my searches, and I am not very Prototype-savy (worked mostly with jQuery).

  • Patryk Padus
    Patryk Padus over 5 years
    New resource with same person in mind and solution to this question: alanstorm.com/magento-custom-form-validation