简体   繁体   中英

Rails form: How to restrict number of characters (digits) in input field

In my devise registration form, I added a new field that needs to take upto 12 digits. To prevent non-digits from being entered, I have used the jquery solution from question 8481132 and it works.

For restricting to 12 digits, I used maxlength as follows:

<div class="field">
    <%= f.label :vat_no, "VAT" %><br/>
    <%= f.number_field :vat_no, :maxlength => 12 %>
</div>

The generated html is

<div class="field">
    <label for="user_vat_no">VAT</label><br>
    <input maxlength="12" size="12" type="number" value="" name="user[vat_no]" id="user_vat_no">
</div>

Looks ok. But my browser (Safari on MacBook) is happily allowing any number of digits.

Check out this page. Instead of :maxlength => 12 , you could do:

<%= f.number_field :vat_no, :max => 999999999999, :min => -999999999999 %>

...since 999999999999 is the highest 12-digit number and -999999999999 is the lowest.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM