-1

I'm trying to check the string entered by users to be used as a topic name for sending notifications with Firebase Cloud Messaging.

As I understand it, the only characters allowed in topic names are:

  • lowercase letters a to z
  • uppercase letters A to Z
  • digits 0 to 9
  • characters - _ . ~ %

The error message from Cloud Messaging when the topic name contains illegal characters is

Notification sent failed: { Error: Topic provided to sendToTopic() must be a string which matches the format "/topics/[a-zA-Z0-9-_.~%]+".

So I try to check for this in my JavaScript code to prevent users from entering the illegal characters. My understanding of checking the regex I obviously wrong though, as the test keeps validating invalid characters as being valid.

The code I'm using is as follows:

let sample = "Test Topic Name 20/20"
let trimmedSample = sample.split(' ').join('');
console.log("trimmedSample = " + trimmedSample);

validateString(trimmedSample);

function validateString(inputtxt) {
  var letters = /[0-9a-zA-Z]+/;
  if (letters.test(inputtxt)) {
    console.log("name is Valid");
  } else {
    console.log("name is Invalid");
  }
}

Even though the topic name includes the invalid '/' character, the check validates it as valid. In fact I'm struggling to find a character it says is invalid.

I'd be grateful to anyone who could point out what I'm going wrong?

Thanks

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807

1 Answers1

0

Your current regular expression checks of the string contains the sample. What you want to do is ensure that it complete matches it with:

var letters = /^[0-9a-zA-Z]+$/;

By using the ^ and $ you ensure that the regular expression must match the entire string for it to succeed, instead of also succeeding on a substring.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • Aha... So I was actually just checking whether 'any' of the string was valid rather than whether it was 'all' valid? Thank you very much for your help. – Warren Harding Dec 01 '20 at 17:08