这将启用pattern
DOM 中所有文本区域的属性并触发 Html5 验证。它还考虑了具有^
or$
运算符的模式,并使用g
Regex 标志进行全局匹配:
$( 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" );
}
}
}
});
});