Magento rewrite functions in validation.js

0

Hi you, today, I will guide how to rewrite functions in validation.js,
validation.js in js/prototype/validation.js, it check validation of all form in Magento website
You can use simple as below code for per form:

var dataForm = new VarienForm('form_id');

Here, I will rewrite validate function.

Step 1: Create a new file
example: custom_validation.js in skin/frontend/packed_theme/theme/js/custom_validation.js

Step 2: Add that file to layout xml
app/design/frontend/packed_theme/theme/layout/page.xml
I will add to page.xml file, you need add after validation.js

<default translate="label" module="page">
    <label>All Pages</label>
    <block type="page/html" name="root" output="toHtml" template="page/3columns.phtml">
        <block type="page/html_head" name="head" as="head">
		...
		...
        <action method="addItem"><type>skin_js</type><name>js/custom_validation.js</name></action>
    </block>
</default>

 

Step 3: Wewrite content in custom_validation.js
I add a notice “New validate function” to first line function.

Object.extend(Validation.prototype, {
//or Object.extend(Validation, {

    validate : function() {

	alert('New validate function');

        var result = false;
        var useTitles = this.options.useTitles;
        var callback = this.options.onElementValidate;
        try {
            if(this.options.stopOnFirst) {
                result = Form.getElements(this.form).all(function(elm) {
                    if (elm.hasClassName('local-validation') && !this.isElementInForm(elm, this.form)) {
                        return true;
                    }
                    return Validation.validate(elm,{useTitle : useTitles, onElementValidate : callback});
                }, this);
            } else {
                result = Form.getElements(this.form).collect(function(elm) {
                    if (elm.hasClassName('local-validation') && !this.isElementInForm(elm, this.form)) {
                        return true;
                    }
                    return Validation.validate(elm,{useTitle : useTitles, onElementValidate : callback});
                }, this).all();
            }
        } catch (e) {
        }
        if(!result && this.options.focusOnError) {
            try{
                Form.getElements(this.form).findAll(function(elm){return $(elm).hasClassName('validation-failed')}).first().focus()
            }
            catch(e){
            }
        }
        this.options.onFormValidate(result, this.form);
        return result;
    }
});

 

From here, you can custom function all follow your want.

Thanks for watching!

About Author

Là một developer rất ham chơi nhưng không ham hố, không ham chơi nhưng rất thích cầm đầu...

Comments are closed.

%d bloggers like this: