Teno
Teno

Reputation: 123

RegEx digit (only 4 digit) and ,

I need validate digits and ', ' but with this condicions:

  1. Only groups of 4 digits separated with ','
  2. no use | (pipe) in the regex.
  3. no white space.
  4. No limit of groups (2345,2345,....n)

Examples:

1234 //correct
1234, //correct
8764,8745 //correct
8974,9874,4567,3456, //correct
8974,9874,4567,3456,2345,3456,3456 //correct


23 //incorrect
2344,23445657,8753 //incorrect
8475,2344565788,8753 //incorrect
8475,34 //incorrect
8475,34,5676,8890 //incorrect

My regex is:

^([\d]{4},?)+$ // but acept:  2344,23445657,8753 ->incorrect

Upvotes: 0

Views: 142

Answers (3)

LeoSanchez
LeoSanchez

Reputation: 169

I imagine you want to use this for validation purposes when submitting something. Regex is a nice tool, but it could give you some undesired behaviors like give you multiple positives.

I wonder if it would be better to create something that breaks down your string and evaluates each piece, like:

let valid1 = "1234,1234,1234";
let valid2 = "1234,1234,1234,4565";
let invalid1 = "1234,1234,12341";
let invalid2 = "1234,12312344,1231";

function validateFourDigitsCommaSeparated(stringToValidate)
{
    let sequences = stringToValidate.split(',');
    let hasInvalidSequence = false;
    let hasValidSequence = false;
    let fourDigitExactlyRegex = /^\d{4}$/;
        
    sequences.forEach(function(sequence) 
      {
        if(sequence.match(fourDigitExactlyRegex))
        {
          hasValidSequence = true;
        }
        else {
          hasInvalidSequence = true;
        }
      }
    );
    
    return hasValidSequence && hasInvalidSequence === false;
}

console.log('valid1', valid1, validateFourDigitsCommaSeparated(valid1));
console.log('valid2', valid2, validateFourDigitsCommaSeparated(valid1));
console.log('invalid1', invalid1, validateFourDigitsCommaSeparated(invalid1));
console.log('invalid2', invalid2, validateFourDigitsCommaSeparated(invalid2));

Upvotes: -1

user15388024
user15388024

Reputation:

A simple solution is

^(\d{4},)*(\d{4})?$

The empty string is not considered by the test cases so it's unclear if it's correct or not.

Upvotes: 1

([\d]{4},?)+ says "4 numbers, and then an optional comma, one or more times, so it will happily accept 12345678 because that's four numbers, no comma (which matches the ,?) and then four numbers. What you want is "always first four numbers" because that's the minimal pattern it needs to match, followed by zero or more groups that have to start with a comma, and finally, an isolated optional comma.

^\d{4}(,\d{4})*,?$

And to verify, we use regex101: https://regex101.com/r/o5MhS9/1

Upvotes: 1

Related Questions