Regex help please

I’m looking for a quick way to validate these rules for a string, in an OnDataChange event
9 characters or less
no imbedded spaces (trailing spaces are ok if that helps with the validation eg if it’s easier to work with the string of a fixed length)
1st character must be A, B, C, D or X
2nd-8th characters may be alpha/numeric;
9th character (if populated) must be alpha, not numeric

It looks like a job for Regex, but I’m not sure how to do the last rule and the variable lengths. Grateful for some guidance, or alternative approaches.

That regex would look like this:

/^[ABCDX]{1}[a-zA-Z0-9]{7}[a-zA-Z]{0,1}$/

and you could to test your string like this:

if (/^[ABCDX]{1}[a-zA-Z0-9]{7}[a-zA-Z]{0,1}$/.test(newValue)) {
    //do stuff
}

Wonderful, thanks Joas!

Almost works.
It will only accept a string that is 8 or 9 characters long.
I’d also like it to accept shorter strings like A123 or B123A

What’s the syntax to make [a-zA-Z0-9]{7} allow a variable number, while still only allowing an alpha in the 9th position (if there is one)?

antonio:
What’s the syntax to make [a-zA-Z0-9]{7} allow a variable number, while still only allowing an alpha in the 9th position (if there is one)?

You can set the min and max number like this:

[a-zA-Z0-9]{3,7}

BTW, here is a short, easy-to-read tutorial for regular expressions in javascript: http://www.javascriptkit.com/javatutors/re.shtml

If you read that, it will make a lot more sense :)

Perfect, thanks!

Hoping someone can help with another regex validation.
It’s for dental work. Valid values:
11-18
21-28
31-38
41-48
51-55
61-65
71-75
81-85

i.e.
must be exactly 2 digits.
first digit must be 1-8
if first digit is 1-4 then second digit must be 1-8
if first digit is 5-8 then second digit must be 1-5

Grateful for assistance!

I think it is easiest to not only use regex for this but something like:

function checkValue(_value) {
	if (/^\d{2}$/.test(_value)) { //_values exists of exactly 2 digits
		var _first = _value[0];  //first character
		var _second = _value[1]; //second character

		if ( (_first >= 1 && _first <= 4) && (_second >= 1 && _second <= 8) ) {
			return true;
		} else if ( (_first >= 5 && _first <= 8) && (_second >= 1 && _second <= 5) ) {
			return true;
		}
	}
	return false;
}

Thanks once again Joas!