1
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?

John
  • 29
  • 4
  • [Unwanted characters like `'`? Do you have something against John O'Reilly?](https://shinesolutions.com/2018/01/08/falsehoods-programmers-believe-about-names-with-examples/) – Quentin Jul 15 '22 at 08:00
  • Does this answer your question? [Regular expression for only characters a-z, A-Z](https://stackoverflow.com/questions/3532053/regular-expression-for-only-characters-a-z-a-z) – Dimitar Jul 15 '22 at 08:12

2 Answers2

0

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.

Dimitar
  • 1,148
  • 8
  • 29
-4
let chars = /[$&+,:;=?@#|'<>.^*()%!-]/g;
chars.test(UserName)

Use Regular expressions ( Regex ) https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions

Roman2021
  • 19
  • 4
  • 2
    Please [avoid link only answers](http://meta.stackoverflow.com/tags/link-only-answers/info). Answers that are "barely more than a link to an external site” [may be deleted](http://stackoverflow.com/help/deleted-answers). – Quentin Jul 15 '22 at 08:00
  • Sorry, I don't think it helps – John Jul 15 '22 at 08:08
  • I've added a regex, try it out. should do – Roman2021 Jul 15 '22 at 08:20