Magento 1.7 JavaScript – Custom Form Validation

javascriptmagento-1.7prototype-jsvalidation

I am trying to implement some custom form validation in Magento using jQuery but I am not sure if I have the correct method.

Basically, I need to validate the following:

  1. Only number fields need to have .00 to validate 1 to 1.00

  2. Letters need to be uppercase

  3. Cannot have number greater than 9.99

  4. No spaces in the fiels

I am thinking to use jQuery and have set about writing something up to validate the form:

<script>
    jQuery(document).ready(function() {
        jQuery.validator.addMethod("integer", function(value, element) {
            return this.optional(element) || /^-?\d+$/.test(value);
        }, "A positive or negative non-decimal number please");

        function(field, length) {
            if (!numericRegex.test(length)) {
                return false;
            }
            return (field.value.length <= parseInt(length, 4));
        },
    }
</script>

The problem is I cannot find the functions for the other validation fields and could do with some assistance please???

Best Answer

Excellent question!

You don't need jQuery for this. You can do this with the built-in Magento form validator. First the javascript to set up the form for validation must be placed in your form template:

<script type="text/javascript">
  var myForm= new VarienForm('[your form id]', true);
</script>

Now prepare your form fields by adding the appropriate css classes.

Cannot have number greater than 9.99

<input type="text" class="required-entry validate-digits-range digits-range-0-9.99"/>

No spaces in the fields

<input type="text" class="required-entry validate-alphanum"/>

That's it! For the more specific use cases you'll have to add custom validation rules:

Only number fields need to have .00 to validate 1 to 1.00

Validation.add('validate-float','Input must be in the form of 0.00',function(v){
    return Validation.get('IsEmpty').test(v) || (!/\./.test(v));
});

Which then is validated with the following:

<input type="text" class="required-entry validate-float"/>

Letters need to be uppercase

This one is similar, the regex must test for a range of uppercase:

Validation.add('validate-uppercase','Input must be in uppercase',function(v){
    return Validation.get('IsEmpty').test(v) || (!/^[A-Z]+$/.test(v));
});

And used like:

<input type="text" class="required-entry validate-uppercase"/>
Related Topic