0

I have two regex patterns

1) re1 = /^[0-9\b]+$/ is for allowing only numbers in the input field

2) re2 = /^(7|75|750)$/ is for allowing first 3 numbers of input field to be "750".

Now, I want to combine both the regex patterns where the input field should allow only 750 as first 3 numbers and remaining digits as numbers. I tried following,

const re3 = /^(7|75|750)|0-9\b]+$/

but it is not working.

Thanks in advance.

3
  • 1
    Use /^(?:7|75|750)[0-9]*$/ but /^7(?:50?)?[0-9]*$/ is better. Commented Aug 23, 2019 at 18:47
  • Try: /^(?:7|75|(?:750[0-9]*))$/ It only allows extra digits if the start is 750. Commented Aug 23, 2019 at 19:37
  • If trying to validate user input I suggest jQuery plugin like nosir.github.io/cleave.js Commented Aug 24, 2019 at 5:49

3 Answers 3

1

You may use

/^(?:7|75|750)[0-9]*$/

Or,

/^7(?:50?)?[0-9]*$/

Details

  • ^ - start of string
  • 7 - a 7 char
  • (?:50?)? - an optional non-capturing group matching 1 or 0 occurrences (i.e. this is optional) of 5 followed with an optional 0
  • [0-9]* - 0+ digits
  • $ - end of string.

Well, if you need to match the backspace char, add \b into the class, /^7(?:50?)?[0-9\b]*$/.

Sign up to request clarification or add additional context in comments.

1 Comment

I don't want 50 to be optional, input should start with 750
0

const regex = /^750\d+$/

const tests = [7503944, 343399, 7445, 7503043434];

tests.forEach(el => console.log(el + ": " + regex.test(el)))

Comments

0

If you want only numbers to be allowed in the input field, then set the input field type as number. It will allow only numbers and you can give re2 regex pattern to check for the first 3 numbers.

function details() {
  const re2 = /^(7|75|750)$/;

  let data = document.getElementById('inputdata').value;
  if (data.match(re2)) {
    alert('Data Valid!')
  } else {
    alert('Data Invalid!')
  }
}
<input type="number" name="" id="inputdata" value=""></input>
<input type="button" name="" value="Check" onclick="details()">

Only e character will be allowed when the type of input field is number because e is an irrational number. I hope it helps.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.