[英]How to specify the maxlength of input tag in terms of the total width of characters
[英]How to specify a maximum number of characters allowed in an input element - Is setting a maxlength attribute enough?
我需要設置輸入元素中允許的最大字符數。 使用maxlength
屬性是否足夠?還是需要進一步的PHP或JavaScript驗證?
這是我到目前為止的內容:
<input type="text" name="field-1" maxlength="20" />
對於客戶端:是的,如規范所述 :
當type屬性的值為“ text”或“ password”時,此屬性指定用戶可以輸入的最大字符數。
盡管,如@RobG所述,您必須在服務器端(例如PHP)上驗證數據。
HTML輸入的maxlength
可以很容易地繞過,例如使用JavaScript。
考慮下面的小提琴,它顯示了問題: http : //jsfiddle.net/2YUca/
在Internet Explorer 9中,maxlenght不適用於<textarea>
字段。 要使其正常工作,您需要添加一些JS。該示例使用jQuery,但是您可以使用標准JS輕松地完成此操作。
$(document).ready(function () {
$('textarea').on('keyup', function () {
// Store the maxlength and value of the field.
if (!maxlength) {
var maxlength = $(this).attr('maxlength');
}
var val = $(this).val();
var vallength = val.length;
// alert
if (vallength >= maxlength) {
alert('Please limit your response to ' + maxlength + ' characters');
$(this).blur();
}
// Trim the field if it has content over the maxlength.
if (vallength > maxlength) {
$(this).val(val.slice(0, maxlength));
}
});
//remove maxlength on blur so that we can reset it later.
$('textarea').on('blur', function () {
delete maxlength;
});
});
使用php可以使用strlen()函數
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.