Limit html text input to a particular number of by

2019-08-14 08:11发布

问题:

Using HTML5 (or less preferably JavaScript) is it possible to limit the maximum length of an input to a particular number of bytes?

I realise that I can limit to a number of characters with:

<input type="text" maxlength="4" />

But that's not good enough because I can input up to four two-byte chars in it.

Obviously I am validating this server-side, but I would like this on the browser-side too.

Edit: Just to be clear, I do wish to be able to support UTF-8. Sorry @elclanrs.

回答1:

this script has a couple minor UX glitches that can be cleaned up, but it does accomplish the basic task outlined when i tested it in chrome:

<input id=myinp />


<script> // bind handlers to input:
   myinp.onkeypress=myinp.onblur=myinp.onpaste= function vld(e){
     var inp=e.target;
     // count bytes used in text:
     if( encodeURIComponent(inp.value).replace(/%[A-F\d]{2,6}/g, 'U').length > 4){
        // if too many bytes, try to reject:
        e.preventDefault;
        inp.value=inp.val||inp.value;
        return false;
     }
     // backup last known good value:
    inp.val=inp.value;
   }

</script>


回答2:

If estimating isn't good enough, I'd filter all the non single-byte chars and count them.