Regex validation by equal number of vowels and consonants

596 Views Asked by At

Can anyone tell me how can I check this by Regex form validation in javascript.

Student Name must contain only alphabets. There must be equal number of Vowels and Consonants.

3

There are 3 best solutions below

0
On

The following code can be used to validate:

  const validateStudentName = (name) => {
  const regExp = /[^a-zA-Z]/;
  const isEven = name.length % 2 == 0;
  const vowels = ['a', 'e', 'i', 'o', 'u'];
  const vowelCount = [...name].reduce((sum, char) => vowels.includes(char.toLowerCase()) ? sum + 1 : sum, 0);
  console.log(!regExp.test(name) && isEven && vowelCount === name.length / 2);
}

validateStudentName("abaci");

0
On

I don't think you can do it using Regex only.

My solution replaces all characters from a string that are not a vowel and returns it's length, same for consonants. Then all you have to do is check if the number of consonants matches the vowels.

const getNumberOfVowels = (string) => string.replace(/[^aeiouAEIOU]/g, "").length;
const getNumberOfConsonants = (string) => string.replace(/[aeiouAEIOU]/g, "").length;

const isAValidName = (name) => {
  const vowels = getNumberOfVowels(name);
  const consonants = getNumberOfConsonants(name);

  return vowels === consonants;
}

console.log(isAValidName("Adam"));
0
On

You will need to create a function that does two things:

  1. Check to see if all characters are letters
  2. Compare the number of vowels to consonants

You will need the following expresisons:

  • /^[a-z]+$/i – Only alpha characters (case-insensitive)
  • /[aeiouy]/ig – Only vowels
  • /[^aeiouy]/ig– Only consonants

const isValidName = (name) =>
  /^[a-z]+$/i.test(name) &&
  name.match(/[aeiouy]/ig).length === name.match(/[^aeiouy]/ig).length;

console.log(isValidName('Gene'));    // Valid
console.log(isValidName('Abby'));    // Valid
console.log(isValidName('Charles')); // Invalid