I have an input that will have input between 3-5 alphanumeric characters.
I want to validate that the user input between 3-5 characters:
/^[A-Za-z0-9]{3,5}$/
But, I want to ignore any alpha characters on form submission, not strip them.
So an input value of "RS032" stays that way in the input on form submission, but the form only actually returns "032"
The question is a little shy of details, but I’m guessing you want to validate everything in the field except letters. So, if the input is
abc1d2e3fghand your requirement is 3 digits, you want that to pass.For a very basic requirement like this, you can intersperse optional
[A-Za-z]*?sets between the other required characters. So, for the 3-numbers requirement, you could use[A-Za-z]*?\d[A-Za-z]*?\d[A-Za-z]*?\d[A-Za-z]*?This requires 3 digits (
\d), and allows any number of letters before, between, or after those digits.If you need to use match/capture groups, instead of just verifying match/no-match this won’t work.
Unless you have a very basic requirement, there is no way that I know of to achieve this with a single RegEx. You’ll likely need to assign the string to another variable, strip the letters, and then validate. By assigning to another variable, you can leave the input in place.
Update in response to question edit:
It sounds like you do want to strip the letters, only you want to do it in the backend. I think that is exactly what you should do, instead of conflating that with validation.
If you really want to do the work client-side, you could use an additional, hidden field, that you update via Javascript when the "source" text changes. On the server you can ignore the "source" field and instead use the "stripped" one.