1

we need to set validation in textfield : "zip code" under checkout process in magento site.

i need to restrict this textfield for maximum 6 digits.

i am using following code for this :

    <input type="text" title="<?php echo $this->__('Zip/Postal Code') ?>"
 name="billing[postcode]" id="billing:postcode" 
 value="<?php echo $this->escapeHtml($this->getAddress()->getPostcode()) ?>"
 class="input-text validate-zip-international
 <?php echo $this->helper('customer/address')->getAttributeValidationClass('postcode') ?>" placeholder="Postal code"/>

please help me to give validation for Restricting only for 6 digits

fresher
  • 917
  • 2
  • 20
  • 55

3 Answers3

2

try this

 function limit(element)
    {
        var max_chars = 6;

        if(element.value.length > max_chars) {
            element.value = element.value.substr(0, max_chars);
        }
    }

 <input type="text" onkeydown="limit(this);" onkeyup="limit(this); "title="<?php echo $this->__('Zip/Postal Code') ?>"
 name="billing[postcode]" id="billing:postcode" 
 value="<?php echo $this->escapeHtml($this->getAddress()->getPostcode()) ?>"
 class="input-text validate-zip-international
 <?php echo $this->helper('customer/address')->getAttributeValidationClass('postcode') ?>" placeholder="Postal code"/>
  • now its displaying like this : http://prntscr.com/a1r0e8 i you can see increment button at the end , i want to remove those. and after i entered 6 digits, if i enter one more digit its increasing the last digit. – fresher Feb 11 '16 at 06:40
  • means 110001 i entered, than if i enter another number its increasing as 110002...... – fresher Feb 11 '16 at 06:41
  • 1
    try it worked for me, are you sure there isn't anything else in the code that is causing this? – Denis Radinski Feb 11 '16 at 06:45
2

The better way is use the pattern attribute:

<input type="number" maxlength="6" pattern="[0-9]{6,}" placeholder="Zip code" required>
Tuan Ha
  • 620
  • 2
  • 8
  • 25
1

This is an example for validating phone number of 10 digits:

Html :

<input type="text" id="phone" name="phone" onkeypress="phoneno()" maxlength="10">

Script file:

<script>        
       function phoneno(){          
        $('#phone').keypress(function(e) {
            var a = [];
            var k = e.which;

            for (i = 48; i < 58; i++)
                a.push(i);

            if (!(a.indexOf(k)>=0))
                e.preventDefault();
        });
    }
   </script>
Rahul Gopi
  • 414
  • 1
  • 16
  • 31