Podcast Episode 7: Validate Password Input for a Special Character

Season 2: One-Liner JavaScript Coding Challenge for Frontend Engineers

Silicon Wat
One-Liner Coding Challenge Podcast
9 min readDec 9, 2021

--

https://podcast.siliconwat.com

One-Liner Buddhist Quote of Week

Don’t be impressed by money, followers, degrees, and titles: be impressed by kindness, integrity, humility, and generosity.
— Buddha

If you’re looking for A Complete Frontend Developer Course for Beginners, check out this textbook written by Thon Ly exclusively for Medium:

A Complete Frontend Developer Textbook for Beginners (2023 Edition)

22 stories

To help you achieve full mastery, all three web languages (HTML, CSS, and JavaScript) are taught together in parallel within a musical context in order to deepen your understanding of their interrelationships in a fun and memorable way!

Episode 6: Validate Password Input for Uppercase and Lowercase

All Episodes

Transcript for Podcast Episode 7

ATTN Frontend Ninja Monks: Can you validate a password for the existence of a special character using only one line of JavaScript code? Come sharpen your coding chops in this episode!

To submit your solution for the next Frontend Coding Challenge, simply go to my Scoreboard webapp, or just mention my hashtag #onelinerpodcast in your Twitter or Facebook post. But if it’s more convenient for you, feel free to reply with your solution in the Comments section of YouTube, Medium, Codepen, or Spotify pertaining to this episode.

If you know a great one-liner Frontend Coding Challenge to recommend for my show, please use my link below to record your message. And if you can speak slowly and clearly, I may even feature your voice in my next episode! Again, if it’s more convenient, feel free to respond in the Comments section instead.

Intro

Every Friday, I send out a Frontend Coding Challenge that can be solved with just one line of JavaScript code. Each episode will have problems for both aspiring Junior and Senior developers. And if you’re the first to submit a correct solution using my hashtag, your username will be recorded in my Scoreboard webapp. Moreover, your winning streaks will be awarded and highlighted in my show. The following Friday, I go over the problems, solutions, and explanations. The topics I cover are modern vanilla JavaScript, CSS and HTML to help you master web development, as well as Data Structures and Algorithms to help you practice for technical interviews. If you want to become a Frontend Ninja Monk, come sharpen your coding chops!

Problem

Last week, this one-liner Frontend Challenge was presented:

<input id="pw" type="password">
<button id="sb">Submit</button>

In the HTML code, there is an input tag with an id attribute of pw and a type attribute of password. There is also a button tag with an id attribute of sb and a text content of Submit.

Level Medium:

When the Submit button is clicked, if the password contains a special character, change the outline color of the input to green; otherwise, change it to red.

Do this in only one line of JavaScript code. You may use regular expressions.

Level Extreme:

Without using regular expressions, solve this problem in only one line of JavaScript code.

Winners

For level medium, the first person to submit a correct answer was a Twitter user with a handle of panhiatha0 on Wednesday at 10:59 am PST.

For level extreme, the first person to submit a correct answer was a YouTube user with a handle of 3iitos on Wednesday at 11:48 am PST.

If you’re listening, you both get a coupon for 90% off of my upcoming Frontend course at Udemy!

Please check out my Scoreboard webapp located at podcast.siliconwat.com for instructions on how to claim your prize.

Great job! 👍 And thanks so much for participating! ❤️

Solution

For level medium, the solution is:

sb.onclick = () => pw.style.outlineColor = /[!@#\$%\^\&*]/.test(pw.value) ? "green" : "red"

Let’s break this down the way the JavaScript engine executes it:

First, let’s analyze:

sb.onclick = () =>

sb is the “id” of the Submit button. In JavaScript, sb becomes a global variable that references the button element. As a DOM element, we can set the onclick attribute of the button by calling its onclick property.

For this onclick variable to work as intended, it needs to be set to a function. This way, it can be called at a later time. In other words, it needs to be set to a “callback” function.

Whenever the button is clicked by the user, the onclick event handler will execute this callback function. To write this callback function in only one line, we write it as an arrow function expression.

Second, let’s analyze:

pw.style.outlineColor =

pw is the “id” of the password input. Like sb, pw becomes a global JavaScript variable that references the input element. As a DOM element, we can get the style attribute of the input by calling its style property.

This returns a JavaScript object with names and values that are rendered into inline CSS properties.

The only thing to keep in mind is that CSS property names are hyphenated, but as JavaScript variable names, they become camelcased.

Here, we plan to set the outlineColor property to the correct color. So, what is the correct color?

To find out, let’s analyze the right side of the assignment operator:

/[!@#\$%\^\&*]/.test(pw.value) ? "green" : "red"

The problem tells us to set the outline color to green if the password contains a special character; otherwise, set it to red.

To express this conditional statement in only one line, we use a ternary operator.

How can we check the password for a special character?

The simplest and easiest way is to take advantage of regular expressions. And it so happens that the regular expression:

[!@#\$%\^\&*]

will match the special characters associated with the numbers 1 through 8 on the keyboard.

If you want to include more special characters, you can simply add them into this list. The only thing to keep in mind is that if the special character is a reserved character, you need to prefix it with a backslash.

As a regular expression, this has a very convenient built-in test() method where we can pass it the string we want to test.

And the string we want to test is the password that was entered by the user which we can get by calling the value property of pw.

If this password passes the test, the method will return true. But if it fails the test, the method will return false.

Per the ternary operation, this boolean will cause green to be returned if true and red if false.

This completes the assignment operation.

Level Extreme:

For level extreme, the solution is:

sb.onclick = () => pw.style.outlineColor = pw.value.split("").some(passwordCharacter => "!@#$%^&*".split("").some(specialCharacter => passwordCharacter === specialCharacter)) ? "green" : "red"

Let’s also break this down the way JavaScript executes it:

First, let’s analyze:

sb.onclick = () => pw.style.outlineColor =

This part of the code is identical to the solution for level medium.

Basically, the onclick handler of the Submit button is set to an arrow function that will update the outline color of the password input.

For a thorough and detailed explanation of this code, please rewind back to the previous solution.

Finally, let’s analyze the ternary operation:

pw.value.split("").some(passwordCharacter => "!@#$%^&*".split("").some(specialCharacter => passwordCharacter === specialCharacter)) ? "green" : "red"

In particular, let’s analyze the conditional expression preceding the question mark which is the only difference compared to the previous solution.

Here, we are asked to implement another way to test for a special character in the password that do not involve using regular expressions.

Regular expressions are so simple and elegant sometimes that it’s almost like cheating. So much so that it takes away most of the challenge of the algorithm. For this reason, most interviewers ban their use in order to really assess your critical thinking and coding skills.

Without using regular expressions, how then can we test for a special character inside a string?

Obviously, we would need to check each password character. And as soon as find that that password character is a special character, the string would pass the test.

To do this in code, we can loop through the password string and special characters using a for of loop. However, this will require more than one line of code.

To see this implementation, check out the link to my codepen in the show notes.

To loop through each password character in only one line:

First, we split up the string into an array of password characters. This way, we can take advantage of all the built-in array methods that loop through each password character.

In code, it is:

pw.value.split("").some(

As we have already discussed, pw.value returns the password as a string. And as a string, we can use its built-in split() method and pass it an empty string in order for it to split up the password into an array of individual characters.

Now, as an array, we can take advantage of the some() method which tests whether at least one element passes the test implemented by the provided callback function.

Here, we want the callback function to be:

passwordCharacter => "!@#$%^&*".split("").some(specialCharacter => passwordCharacter === specialCharacter)

For each passwordCharacter, we want the callback function to test if it’s a specialCharacter.

A clever trick to achieve this is to create a string of specialCharacters. Then, like before, we can use the split() method to split this string into an array of specialCharacters. And like before, as an array, we can take advantage of the some() method again to test whether the passwordCharacter matches at least one of the specialCharacters.

This clever use of the some() method inside another some() method is equivalent to using a for of loop inside another for of loop in the alternate implementation. Therefore, both of which equate to a Big O of quadratic time: O(n²)

This concludes the conditional expression in our ternary operation.

References:

  1. https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onclick
  2. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions
  3. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator
  4. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
  5. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Groups_and_Ranges
  6. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test
  7. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split
  8. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some
  9. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of

Show Notes

Thanks so much for tuning in! I hope you learned something new today! By the way, in the show notes, there are links to my CodePen with all the problems and all the solutions:

As well as a YouTube recording of this episode:

And a transcript on Medium.

Remember to subscribe to my podcast and YouTube channel to be notified the instant I release the next episode!

Next Problem

For this week, your one-liner Frontend Challenge is this:

<span id="countdown">10</span>

In the HTML code, there is a span tag with an id attribute of countdown and a text content of the number 10.

Level Easy:

In only one line of JavaScript code, decrement the number in the text content. Your code should work for any default number in the text content.

Level Medium:

In only one line of JavaScript code, decrement the number in the text content every 1 second.

Level Hard:

Finally, in only one line of JavaScript code, decrement the number in the text content every 1 second. However, when the number reaches 0, STOP.

Outro

To submit your answer to this challenge, simply include the hashtag #onelinerpodcast in your Twitter or Facebook post. Or, you can go to my Scoreboard webapp located at podcast.siliconwat.com.

If you’re the first person to submit a correct solution, I will give you a coupon for 90% off of my upcoming Frontend Course at Udemy.

Again, don’t forget to subscribe to my podcast and YouTube channel to be notified the instant I release the next problem.

Lastly, if you can think of a great one-liner Frontend Challenge to recommend for this show, please call in and leave a voice message! Thanks so much!

Episode 8: Count Down

All Episodes

When you use my referral link above 👆 to become a Medium member, all proceeds will be donated towards the construction of the Silicon Wat Campus for children in Ukraine and Cambodia ❤️

--

--