Validating name in visual studio code

Viewed 49
var userName = input.question('Please enter your name: '); //Asking User to enter their Name.
while (userName.includes('.')) {
    console.log ("Invalid Name!");
    var userName = input.question('Please enter your name: '); //Asking User to enter their Name.
}

Above code will ask the user his/her name and store it in "userName". Then it will validate using .includes to check unwanted characters and numbers.

I want to validate if userName has numbers or unwanted characters such as "?/.,;'[]{}|&^%@" etc. I have tried using .includes and validate if a name has "." However, I'm not sure how to go about from there to validate the rest.

After the while checks that it contains the unwanted characters, it will re-prompt the user to enter a new name and it will check again until it returns false.

Is there a solution to this?

2 Answers

You can use REGEX to search for non-alphabetic or space characters in the string:

userName.search(/^[a-zA-Z\s]+$/)

The response will be 0 or -1. 0 means that no characters except A-Z, a-z and space were found, -1 means the contrary.

Edit: I found similar question with more detailed answers here.

Related