read

The Problem

On a recent project, I was tasked with building a monogram tool that would allow visitors to preview and add a 3-letter monogram to various products in the store. The end result looked as displayed below. Pretty cool!

Bosca

After a few weeks, the fulfillment department noticed that many users were entering lowercase letters. This was a problem as they do not have lowercase glyphs available for some of their typefaces. As such, I was asked to make sure that only uppercase letters were entered into the ""Add a Monogram"" field.

The Solution

My solution was to develop a custom validation method, specific to the product detail page/form where the user will be entering his or her monogram data (as you can probably tell from the photo, the ""Add a Monogram"" field is a custom option for the particular product).

Validation on the product detail page is triggered when the submit event of the VarienForm object is executed.

We also have access to the Validation object.

To check to make sure that any input was indeed all uppercase, I added my own, very simple validation method using the Validation.add method.

var monoProductAddToCartForm = new VarienForm('monogram_product_addtocart_form');
monoProductAddToCartForm.submit = function(button, url) {
    /**
     * Add a new validation method
     */
    Validation.add('validate-uppercase', 'Only uppercase letters are allowed', function(field_value) {
        /**
        * Make sure that field value does not contain lowercase letters
        */
        if (field_value.match(/[a-z]/)) {
            /** Has lower case letters return false **/
            return false;
        }
        return true;
    });

     /**
      * ... Rest of Submit Function Directives ...
      */
};

The key element here is the Validation.add method. The syntax is as follows:

Validation.add(className, errorMessage, callback)

The first parameter is a string: the class name that you can add to your input field, select menu, etc..

In this case, I added it to my custom option input field. (To prevent any conflicts, I actually added a new custom option type called ""monogram"", heavily borrowing from the ""text"" fieldtype. This allowed me to add the class to just the monogram field type. )

The second parameter is the error message to display in the event that the callback method returns false and the validation fails.

The callback actually runs the validation; it accepts the field's value as its parameter and should return a boolean value, true if the validation passes, false otherwise.

Blog Logo

Phil Birnie


Published

Image

Phil Birnie

Full Stack Web Developer from Columbus, Ohio

Back to Overview