user15249038
user15249038

Reputation:

Validating a string with given conditions

I am asked to create a function that takes a string to check whether the string is valid or not.

A valid string has the following conditions.

Exactly 4 or 6 characters.

Only numerical characters (0-9).

No whitespace

My solution does not work.

function test(num){
  return num.length === 4 || num.length === 6;
}

console.log(test("123445"),true);

console.log(test("801264"),true);

console.log(test("451352"),true);

console.log(test("881234"),true);

console.log(test("as89abc1"),false);

console.log(test("    "),false);

console.log(test(" 4983 "),false);

console.log(test("123 "),false);

Upvotes: 1

Views: 51

Answers (1)

The fourth bird
The fourth bird

Reputation: 163517

You are only checking the length of the string, and not if it consists of only digits.

You might also use a pattern to check for 4 or 6 digits

const test = num => /^(?:\d{4}|\d{6}$)/.test(num);

[
  "123445",
  "801264",
  "451352",
  "881234",
  "as89abc1",
  "    ",
  " 4983 ",
  "123 "
].forEach(s => console.log(`${s} ==> ${test(s)}`));

Upvotes: 2

Related Questions