Skip to content
Advertisement

An underscore, a dot and a dash must always be followed by one or more alphanumeric characters without using Regex

I’m working on a school assignment that validates emails without using Regex. The premise of this exercise is to learn about methods and to practice our critical thinking. I understand that the code can be reduced to fewer lines.

Right now, I need to check all conditions for the prefix of an email (The characters before ‘@’):

  • It contains at least one character.
  • It contains only alphanumeric characters, underscores(‘_’), periods(‘.’), and dashes(‘-’).
  • An underscore, a period, or a dash must always be followed by one or more alphanumeric characters.
  • The first character must be alphanumeric.

Examples of valid prefixes are: “abc-d”, “abc.def”, “abc”, “abc_def”.
Examples of invalid prefixes are: “abc-”, “abc..d”, “.abc”, “abc#def”.

I’m having a hard time figuring out the third condition. So far, I have these methods that meet the other conditions.

JavaScript

Advertisement

Answer

Let’s look at your list:

  • It contains at least one character.
  • It contains only alphanumeric characters, underscores(‘_’), periods(‘.’), and dashes(‘-’).
  • An underscore, a period, or a dash must always be followed by one or more alphanumeric characters.
  • The first character must be alphanumeric.

As you say, 1, 2, and 4 are easy. Here’s what I would do. My first line would check length and return false if incorrect. I would then iterate over the characters. Inside the loop;

  • set boolean lastWasSpecial = false.
  • Check that it’s a legal character (condition 2)
  • If index == 0, check that it’s alphanumeric (condition 4)
  • If it’s one of the specials:
    • If lastWasSpecial is set, return false
    • Set lastWasSpecial = true;
  • else set lastWasSpecial = false again

Should be about 10 lines of easily-readable code.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement