Bạn có thể tự thực hiện việc này với setCustomValidity()
. Bằng cách này, this.checkValidity()
sẽ trả lời bất kỳ quy tắc nào bạn muốn áp dụng cho phần tử của mình. Tôi không nghĩ rằng this.validity.patternMismatch
có thể đặt theo cách thủ công, nhưng bạn có thể sử dụng thuộc tính của riêng mình thay thế, nếu cần.
http://jsfiddle.net/yanndinendal/jbtRU/22/
$('#test').keyup(validateTextarea);
function validateTextarea() {
var errorMsg = "Please match the format requested.";
var textarea = this;
var pattern = new RegExp('^' + $(textarea).attr('pattern') + '$');
// check each line of text
$.each($(this).val().split("\n"), function() {
// check if the line matches the pattern
var hasError = !this.match(pattern);
if (typeof textarea.setCustomValidity === 'function') {
textarea.setCustomValidity(hasError ? errorMsg : '');
} else {
// Not supported by the browser, fallback to manual error display...
$(textarea).toggleClass('error', !!hasError);
$(textarea).toggleClass('ok', !hasError);
if (hasError) {
$(textarea).attr('title', errorMsg);
} else {
$(textarea).removeAttr('title');
}
}
return !hasError;
});
}
Nguồn
2014-01-23 14:59:00
vẻ [ 'textarea' không có 'thuộc tính pattern'] (https: // developer.mozilla.org/en-US/docs/HTML/HTML_Elements/textarea?redirectlocale=en-US&redirectslug=HTML%2FElement%2Ftextarea), vì vậy rất có thể các trình duyệt sẽ bỏ qua nó. – Passerby