1

I had a list of different formats for the string. When a string produces a string of something, the users must key-in the format of that particular string.

If the given string are

A-01-13A

(One alphabet, follow by dash, two numbers, follow by dash, two numbers, and one alphabet)

or

A-01-13

(One alphabet, follow by dash, two numbers, follow by dash, two numbers)


The user's key-in string is validated below:

B-13-99

B-14-11A

The user's key-in string is NOT validated below:

B-13-100


What is the best way to validate the given string using Regex or other methods in Javascript?

3
  • Have you tried any regex? Sep 2, 2017 at 8:37
  • Nope. I'm new to regex.
    – Abel
    Sep 2, 2017 at 8:38
  • @AbelChun: Did you solve your problem? Sep 6, 2017 at 6:32

3 Answers 3

9

Just use simple regex:

const userKeyRegExp = /^[A-Z]\-[0-9]{2}\-[0-9]{2}[A-Z]?$/;

const valid = userKeyRegExp.test('A-01-13A');

console.log(valid);
1
  • 1
    When using a regular expression to validate a string, test is more semantic as it returns true or false.
    – RobG
    Sep 2, 2017 at 8:45
5

The RegExp expression you are looking for is:

^([a-zA-Z]{1}-[0-9]{2}-[0-9]{2}[a-zA-Z]{0,1})$

This means: Starts with one character, followed by a dash, followed by two numbers, followed by a dash, followed by two numbers, ends with one or none characters.

You can play with it in Regex101 or you can leverage in Javascript as follows:

/** @const {!RegExp} Code pattern to validate. */
const CODE_PATTERN = /^([a-zA-Z]{1}-[0-9]{2}-[0-9]{2}[a-zA-Z]{0,1})$/;


/**
 * Validate that a certain code matches expected RegExp.
 * Uses CODE_PATTERN to validate.
 * @param {string} code - Code to be validated.
 * @return {bool} Whether provided code matches pattern.
 */
const validateCode = function(code) {
  return CODE_PATTERN.test(code);
};



// Test sample of codes.
const testCodes = [
  'A-01-13A',
  'A-01-13',
  'B-13-99',
  'B-14-11A',
  'B-13-100'
];
for (code of testCodes) {
  const isValidCode = validateCode(code);
  console.log(isValidCode);
}

0

you can do it in the following way

function validate(str){
    return str.match(/^[A-Z]-\d{2}-\d{2}[A-Z]?$/) !== null;
}


console.log(validate('A-01-13A'));
console.log(validate('A-01-13'));
console.log(validate('B-13-99'));
console.log(validate('B-14-11A'));
console.log(validate('B-13-100'));

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.