2016-07-07 490 views
2

我嘗試在jQuery中創建一個simpel表單取值函數,但在某些方面,此函數始終返回de輸入爲false。你能幫我嗎?jQuery正則表達式匹配函數總是返回false

<!DOCTYPE html> 
<html lang="en"> 
<head> 
    <title>Bootstrap Example</title> 
    <meta charset="utf-8"> 
    <meta name="viewport" content="width=device-width, initial-scale=1"> 
    <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"> 
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> 
    <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script> 
    <style>input.notoke { border: 1px solid red; }</style> 
</head> 
<body> 
<script> 
$(document).ready(function(){ 
    $("form#validate :input").each(function(){ 
    $(this).on("change paste keyup", function() { 

     if ($(this).val().match($(this).attr('data-regex'))){ 
     $(this).removeClass('notoke'); 
     } else { 
     $(this).addClass('notoke'); 
     } 

    }); 
    }); 
}); 
</script> 

<div class="container-fluid"> 
    <div class="row"> 
    <div class="col-sm-12"> 
     <h3>Formulier</h3> 
     <form role="form" id="validate"> 
    <div class="form-group"> 
    <label for="email">Email address:</label> 
    <input type="text" class="form-control" id="email" data-regex="^[A-Z0-9._%+-][email protected][A-Z0-9.-]+.[A-Z]{2,4}$"> 
    </div> 
    <div class="form-group"> 
    <label for="pwd">Password:</label> 
    <input type="password" class="form-control" id="pwd" data-regex="/^[a-z0-9_-]{6,18}$/"> 
    </div> 
    <div class="checkbox"> 
    <label><input type="checkbox"> Remember me</label> 
    </div> 
    <button type="submit" class="btn btn-default">Submit</button> 
</form> </div> 
    </div> 
</div> 

</body> 
</html> 

我看不出是我錯了......你能幫我嗎?我試着用'alert'來查看$(this).val和$(this).attr('data-regex')的值,但這對我來說似乎很好。

回答

6

任何從DOM閱讀是字符串

您對使用RegExp構造函數和傳遞給它的字符串轉換爲正則表達式。

if ($(this).val().match(new RegExp($(this).attr('data-regex')))) { 
         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 

此外,請注意,字符串中不需要分隔符斜槓。

而且一定要仔細,如果需要

逃避一些元字符例如,匹配數字使用

\\d 

,我也會推薦使用RegExp#test以檢查串滿足正則表達式,而不是的String#match

if (new RegExp($(this).data('regex')).test($(this).val())) { 

而且, jQuery代碼可以縮短。

$("form#validate :input").on("change paste keyup", function() { 
    $(this).toggleClass('notoke', !new RegExp($(this).data('regex')).test($(this).val())); 
}); 

Working Demo

+0

感謝您爲您的輸入反應快。不幸的是,你的建議給我留下了一個錯誤:** Uncaught TypeError:$(...)。data(...)。test不是一個函數** –

+0

@ FJ-web對不起,打錯了。錯誤的括號。使用'new RegExp($(this).data('regex'))。test($(this).val())'。 – Tushar

+0

Thnx。但結果仍然是錯誤的。我的data-regex屬性有問題嗎? –