2015-09-27 80 views
0

我試圖讓Jquery使用正則表達式驗證表單,但以非常規方式。表單ID是「sumform」,表單內的textarea被稱爲「summary」。我在包含正則表達式的表單外有另一個輸入字段(id =「terms_out」)。我似乎無法讓Jquery驗證程序將「terms_out」的值識別爲正則表達式。當用戶輸入任何內容時,我的表單都會被提交。使用包含RegEx和Jquery的輸入字段來驗證表單

我已經試過,但它不工作...

$(function() { 
    $.validator.addMethod("regex", function(value, element, regexpr) { 
    return regexpr.test(value); 
    }, "Sorry, you haven't used all the terms.");  

    $("#sumform").validate({ 
    rules: { 
     summary: { 
      required: true, 
      regex: '#terms_out', 
     } 
    } 
    }); 
}); 

這工作完全正常......

$(function() { 
$.validator.addMethod("regex", function(value, element, regexpr) {   
return regexpr.test(value); 
}, "Sorry, you haven't used all the terms.");  

    $("#myForm").validate({ 
     rules: { 
      experience: { 
       required: true, 
       regex: /^(?=[\S\s]*\bcell|cells|cell\b)(?=[\S\s]*\bDNA|DNA|DNA\b)(?=[\S\s]*\bsense|senses|sense\b)(?=[\S\s]*\brespond|responds|respond\b)(?=[\S\s]*\benergy|energy|energy\b)(?=[\S\s]*\bgrow|grows|grow\b)(?=[\S\s]*\bdevelop|develops|develop\b)(?=[\S\s]*\breproduce|reproduces|reproduce\b)/ 
      } 
     } 
    }); 
}); 

我在這所以任何幫助非常新會不勝感激。謝謝!

回答

0

您可以切換:

regex: '#terms_out',

到:

regex: $("#terms_out").val(),

編輯:

$("#Form").validate({ 
     rules: { 
      summary: { 
       required: true, 
       regex: new RegExp($("#terms_out").val()) 
      } 
     } 
    }); 

這將需要從文本區域的值,並將其插入到ruls

+0

感謝您的幫助薩爾,但這似乎並不奏效。以下是我的摘要表單的鏈接http://wisscience7-lessons.weebly.com/summary-2-1.html - 「terms_out」字段位於左上角。 – firenemus

+0

嗨,我調試了你的代碼,問題是你的validate函數在你向'terms_out'添加正則表達式之前被調用,請確保你的代碼以正確的順序運行 – Saar

+0

再次感謝Saar的幫助。我很抱歉,但是如何在正則表達式可用之前知道validate函數正在被調用?我之前成功地使用了這個方法,除了它只是一個簡單的數值,它將進入輸入字段。再次謝謝你。 – firenemus