2011-12-03 39 views
1
$('form').find('input[pattern],textarea[pattern]').each(function(){ 
    if(!$(this).val().match($(this).prop('pattern'))){ 
     $(this).addClass('error'); 
    } 
    }); 


<textarea name=... required pattern=^.{10,255}$></textarea> 

基本上,如果值與模式不匹配,則會添加類(錯誤)。然而,即使我僅輸入1-9個字符,類也不會被添加到textarea。爲什麼jQuery HTML5後備工作不起作用?

+1

在HTML5中它的正確使用'數據pattern',不'pattern',因爲這不是一個有效的屬性。 'data- *'是。 –

+0

模式爲HTML5 http://dev.w3.org/html5/spec/common-input-element-attributes.html#the-pattern-attribute – numbers1311407

+0

您忘了將'pattern'屬性值放在引號中... –

回答

1

在HTML5中,模式可能被解釋爲正則表達式,但這裏只是一個字符串。你需要製作一個正則表達式。

new RegExp($(this).attr('pattern')) 

此外,您可能想扔周圍的屬性,一些報價:

pattern="^.{10,255}"