将html文本输入限制为特定的字节数? [英] Limit html text input to a particular number of bytes?
问题描述
使用HTML5(或者更不用说JavaScript)可以限制输入
的最大长度为特定字节数量?
我意识到我可以限制为多个字符:
< input type =文字maxlength =4/>
但这还不够好,因为我最多可以输入四个双字节字符。 p>
显然,我正在验证这个服务器端,但我也希望在浏览器端也能这样。
编辑:为了清楚起见,我希望能够支持UTF-8。对不起@elclanrs。
这个脚本有一些可以清理的UX小故障,但它确实完成了基本任务概述,当我测试它在铬:
< input id = myinp />
< script> //绑定处理程序输入:
myinp.onkeypress = myinp.onblur = myinp.onpaste = function vld(e){
var inp = e.target;
//在文本中使用的字节数:
if(encodeURIComponent(inp.value).replace(/%[AF \d] {2,6} / g,'U')。length> ; 4){
//如果字节太多,请尝试拒绝:
e.preventDefault;
inp.value = inp.val || inp.value;
返回false;
}
//备份最后一次已知的良好值:
inp.val = inp.value;
}
< / script>
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.
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>
这篇关于将html文本输入限制为特定的字节数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!