Regex for checking strings


So, we all have done this... more than we want to admit! We are so focused on the logic implementation, that sometimes we forget the easy tasks!

So let's say that we have a simple form that we want the user to update the username! We want the user name to be:

  • Alphanumeric with spaces, but not only spaces
  • Should not have any symbols
  • Should not be only numbers

 

updateUserName() {
const regex = /^[\w ]+$/;

if (this.userName && this.userName.trim().length > 0 && regex.test(this.userName)) {
this.user.name = this.userName;
console.log('User name updated: ' + this.user.name);
}
else {
console.log('User name must not be null, empty or consist only of white spaces. Only alphabets, numbers, and whitespace are allowed...');
}
}

No files yet, migration hasn't completed yet!