简体   繁体   中英

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. The form id is "sumform" and a textarea within the form is called "summary." I have another input field (id="terms_out") outside of the form which contains the regular expression. I can't seem to get the Jquery validator to recognize the value of "terms_out" as a regex. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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