简体   繁体   English

使用包含RegEx和Jquery的输入字段来验证表单

[英]Using an input field containing a RegEx and Jquery to validate a form

I'm attempting to have Jquery validate a form using regular expression, but in an unconventional way. 我正在尝试让Jquery使用正则表达式来验证表单,但是以一种非常规的方式。 The form id is "sumform" and a textarea within the form is called "summary." 表单ID为“摘要”,表单中的文本区域称为“摘要”。 I have another input field (id="terms_out") outside of the form which contains the regular expression. 在包含正则表达式的表单之外,我还有另一个输入字段(id =“ terms_out”)。 I can't seem to get the Jquery validator to recognize the value of "terms_out" as a regex. 我似乎无法让Jquery验证器将“ terms_out”的值识别为正则表达式。 My form ends up being submitted when the user enters anything. 当用户输入任何内容时,我的表单最终将被提交。

I've tried this but it doesn't work... 我已经尝试过了,但是没有用...

$(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',
       }
     }
  });
});

This works perfectly fine... 这工作得很好...

$(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)/
           }
       }
   });
});

I'm very new at this so any help would be greatly appreciated. 我对此非常陌生,因此不胜感激。 Thank you! 谢谢!

You can switch: 您可以切换:

regex: '#terms_out',

to: 至:

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

EDIT: 编辑:

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

That will take the value from the text area and insert it to ruls 这将从文本区域获取值并将其插入规则

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM