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