user1899829
user1899829

Reputation: 407

Converting ## to number regex

I am holding in a field the validation format that I would need. I need to convert different ## into a regex validation.

Is there a simple replace that can do this for me. for example, i need to validate the account number. sometimes it might need to be ###-###, or I'll get ####### or ##-####. depending what is in the id="validationrule" field I'm looking for

regex = $('#validationrule').replace("#", "[0/9]");

It also has to take into consideration that sometimes there is a dash in there.

Upvotes: 0

Views: 344

Answers (2)

Tomas Langkaas
Tomas Langkaas

Reputation: 4731

Your question seems to be about creating regexes from a string variable (which you get from an input field that specifies the validation format).

  • "###-###" might turn into /^\d{3}\-\d{3}$/
  • "#######" might turn into /^\d{7}$/

If your validation format is built from the 2 characters # and -, this would work:

function createValidationRegEx(format){
  format = format
    .replace(/[^#\-]/g, '') //remove other chars
    .replace(/#/g, '\\d')   //convert # to \d
    .replace(/\-/g, '\\-'); //convert - to \-
  return new RegExp('^' + format + '$', 'g');
}

//create regexes
var format1 = createValidationRegEx('###-###');
var format2 = createValidationRegEx('#######');

//test regexes
console.log(format1.test('123-456')); // true
console.log(format2.test('123-456')); // false

console.log(format1.test('1234567')); // false
console.log(format2.test('1234567')); // true

Please note that you need to pay attention to which characters needs to be escaped when creating regexes from strings. This answer provides more details about how to solve this more generally, if you want to build more complex solutions.

Upvotes: 1

guest271314
guest271314

Reputation: 1

If you are trying to replace the .value of an <input> element you can use .val(function), return replacement string from .replace() inside of function, chain .val() to assign result to regex. Use RegExp constructor with g flag to replace all matches of the RegExp supplied to .replace() to match characters against at string.

var regex = $("#validationrule").val(function(_, val) {
              return val.replace("#", "[0/9]");
            }).val();

console.log(regex);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<input id="validationrule" value="#">

Upvotes: 0

Related Questions