Home > database >  check if an input is of this form
check if an input is of this form

Time:02-05

I have a code where the user enters multiple strings and I store them in an array, then I want to check if all the inputs are valid.

An input valid is a number with the same character repeated 3 times.
For example : '333', '999', '222', ...

What I have tried :

let valid = true;
inputs.forEach((input) => {
    if (input.length !== 3 ||  isNaN(input)) {
      valid = false;
    } else {
      const first = input[0];
      for (let i = 1; i < 3; i  ) {
          console.log(first,input[i])
        if (input[i] !== first) {
            valid = false;
        }
      }
    }
  });
console.log(valid);

this code is working and I want to know if can I do better it seems like I used too much code for this simple task and I want to know if there is a simpler code when I searched in the interned they suggest rejex but this is so complicated for me thank you for helping me

CodePudding user response:

You could use Array#every.

let valid = inputs.every(s => s.length === 3 && !isNaN(s) 
                  && [...s].every(c => c === s[0]));

This could be shortened with a regular expression:

let valid = inputs.every(s => /^(\d)\1{2}$/.test(s));

CodePudding user response:

First of all for a beginner your solution is good and correct congrats however you can optimize it and make it simpler

  1. you can use every instead of forEach there is no need to check all the inputs once you find an invalid one
  2. instead of loop through the input you can check if it is not divisible by 111 ;)
if(parseInt(input) % 111 !== 0) valid = false;
  • Related