验证文本字段限制为 6 位数字

Validation for textfield to restrict for 6 digits

本文关键字:数字 文本 字段 验证      更新时间:2023-09-26

我们需要在 Magento 站点的结帐流程下的文本字段:"邮政编码"中设置验证。

我需要将此文本字段限制为最多 6 位数字。

我为此使用以下代码:

    <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"/>

请帮助我验证仅限制 6 位数字

试试这个

 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"/>

更好的方法是使用 pattern 属性:

<input type="number" maxlength="6" pattern="[0-9]{6,}" placeholder="Zip code" required>

以下是验证 10 位电话号码的示例:

目录 :

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

脚本文件:

<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>