当我在javascript中使用textarea.checkValidity()或textarea.validity.valid时,这两个值总是返回true,我做错了什么?
<textarea name="test" pattern="[a-z]{1,30}(,[a-z]{1,30})*" id="test"></textarea>?
jQuery('#test').on('keyup', function() {
jQuery(this).parent().append('<p>' + this.checkValidity() + ' ' +
this.validity.patternMismatch + '</p>');
});
Run Code Online (Sandbox Code Playgroud)
你可以自己实现这个setCustomValidity().这样,this.checkValidity()将回复您要应用于元素的任何规则.我不认为this.validity.patternMismatch可以手动设置,但如果需要,您可以使用自己的属性.
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;
});
}
Run Code Online (Sandbox Code Playgroud)
这将启用patternDOM中所有textareas 的属性并触发Html5验证.它还考虑了具有^or $运算符的模式,并使用gRegex标志进行全局匹配:
$( document ).ready( function() {
var errorMessage = "Please match the requested format.";
$( this ).find( "textarea" ).on( "input change propertychange", function() {
var pattern = $( this ).attr( "pattern" );
if(typeof pattern !== typeof undefined && pattern !== false)
{
var patternRegex = new RegExp( "^" + pattern.replace(/^\^|\$$/g, '') + "$", "g" );
hasError = !$( this ).val().match( patternRegex );
if ( typeof this.setCustomValidity === "function")
{
this.setCustomValidity( hasError ? errorMessage : "" );
}
else
{
$( this ).toggleClass( "error", !!hasError );
$( this ).toggleClass( "ok", !hasError );
if ( hasError )
{
$( this ).attr( "title", errorMessage );
}
else
{
$( this ).removeAttr( "title" );
}
}
}
});
});
Run Code Online (Sandbox Code Playgroud)