This question already has answers here:
Match exact string
(3 answers)
Closed 2 years ago.
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
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.
Related
This question already has answers here:
Remove not alphanumeric characters from string
(10 answers)
Regular expression to remove anything but alphabets and '[single quote]
(1 answer)
javascript regex to return letters only
(6 answers)
Ignoring invisible characters in RegEx
(2 answers)
Closed 2 years ago.
I am performing a validation in html text box which should pass only alphabets(a-z/A-Z) and few special characters like (*,& etc..). Otherwise it should show error some error.
I had written a JavaScript function which does the same.
function removeInvalidCharacters(selectedElement) {
if (selectedElement && typeof selectedElement.val() !== typeof undefined && selectedElement.val() != "") {
selectedElement.val(selectedElement.val().replace(/[\u0000-\u001F]|[\u007F-\u00A0]/g, "").replace(/\\f/g, "").replace(/%/g,""));
}
}
I am filtering selectedElement before passing to the function removeInvalidCharacters.
$("#name").val(toASCII($("#name").val()));
var selectedElement = $("#name").val();
But now I am facing a scenario in which empty characters, blank characters, invisible characters and whitespace characters are bypassing my regex. I could see some invisible characters are present in my name field. I want to replace these characters.
In further investigation I could found that Invisible characters - ASCII
characters mentioned in this link are the culprits. I need to have a regex to catch them and replace them.
Eg: AAAAAAAAAAAA‎AAAAAAAAAAA is the value in text field. Now if we check $("#name").val().length, it gives 24 ,even though we could see only 23 characters. I need to remove that hidden character.
Please help me with this scenario. Hope my query is clear
UPDATE:
var result = selectedElement.replace(/[\u200B-\u200D\uFEFF]/g, ''); fixed my problem.
Thank you all for the support.
If you want to allow only (a-z/A-Z) like you mention, try this:
str = str.replace(/[^a-zA-Z]/g, '');
Include the chars you want to keep instead of the ones you do not want, since that list may be incomplete
Otherwise look here: Remove zero-width space characters from a JavaScript string
const val = `AAAAAAAAAAAA‎AAAA**AAAAAAA`;
const cleaned = val.replace(/[^A-Za-z*]/g,"");
console.log(val.length,cleaned.length);
I am trying to use regex in JavaScript to verify if a given password has alphabetic, numeric, and a special character. However, everything I have tried doesn't work
I have tried using
/^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[!#"#%$&])[A-Za-z0-9!#"#%$&]{8,30}$/gm
and creating separate regex variables for alphabetic, numeric, and special characters:
let alpha = /^[A-Za-z]+$/i
let numer = /^[0-9]+$/i
let special = /^[!##$%^&*(),.?;":{}|<>']/i
Picture of My Code
When I log the password.match(regex) to the console I always see null
Try this:
^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[^\da-zA-Z]).{8,15}$
This is from a post a long time ago. There are probably others as well. A simple search of SO will find more examples.1
Here is a visualisation of the regular expression:
Debuggex Demo
I would personally go for separate regexes, the issue with your current regexes is that you have ^ at the start and $ at the end. Which means that the password must only contain [A-Za-z] from start to finish. Then you check if the password only contains [0-9] from start to finish.
const regexes = {
alpha: /[A-Za-z]/,
number: /[0-9]/,
special: /[!##$%^&*(),.?;":{}|<>']/,
length: /^.{8,30}$/
};
["dgXHUYuDdp", "zMv4qQfZj3", "4JXyrsq!J0", "a5Z!"].forEach(password => {
let valid = Object.values(regexes).every(regex => password.match(regex));
console.log(
"password: " + JSON.stringify(password) + "\n" +
"valid: " + valid
);
});
While I suspect it may be possible to write a regex which will do position/seuqnce independent matching, my head hurts just thinking about. So even if I could work out a way of doing it, I would not implement it - code needs to be readable and parseable by human beings. Looking at what you have presented here, I think I'm a lot more familiar with regexes than you are - so even more reason not to do this.
Your alpha / numer / special regexes will only match a string containing letters, numbers or special characters, not a mixture. If you change them thus, then you can check for a match of all three (and escape the meta characters in the special regex):
let alpha = /[A-Za-z]/i;
let numer = /[0-9]/;
let special = /[!##$%\^&*(),\.?;":{}|<>\']/;
if (password.match(alpha) && password.match(numer) && password.match(speicial)) {
This question already has an answer here:
All characters in a string must match regex
(1 answer)
Closed 3 years ago.
I have to check whether a given string contains pipeline and comma (|,) in a string and throw error if it contain the same.throwing error part i can handle but facing issue while creating regex for this.
i have used this regex to validate it [^|,] but its not working.
String is "Equinix | Megaport" but my vregex is not throwing error as it contains | in it
In JavaScript, try:
var subject = "Equinix | Megaport";
if (/^[^|,]+$/.test(subject)) {
document.write('No bad character(s)');
} else {
document.write('Contains bad character(s)');
};
Also note that I slightly changed your pattern to include the + operator after your negated character class, which means match the character class between one and unlimited times.
This question already has answers here:
Return true/false for a matched/not matched regex
(5 answers)
Closed 3 years ago.
I'm trying to match an entire string against a regex formula. This is for validating if a phone number field is likely correct (just based on allowed characters, anyone can make up an number). I've played with Regex before but never truly understood the nuances that make it powerful.
Below I have my dummy phone number and I have the regex I'm using. As you can see I'm simply comparing the length of the match vs the length of the string and if they match the number must be valid.
Is there a way to get a simple true/false reply from a Regex check on an entire string?
var num = '+1 (888) 456-7896';
var regex = /[0-9+ ()-]*$/;
var found = num.match(regex);
console.log(found[0].length);
console.log(num.length);
You can use test()
var found = regex.test(num);
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Password validation regex
between 8 and 16 characters, with at least 1 character from each of the 3 character classes -alphabetic upper and lower case, numeric, symbols.
I have this code, but it doesn't work, when I write more than 16 characters, gives it as valid, but it should not; the it should to work ok with 3 character classes, but it works with 4, where's my mistake??
http://jsbin.com/ugesow/1/edit
<label for="pass">Enter Pass: </label>
<input type="text" id="pass" onkeyup="validate()">
Script
function validate() {
valor = document.getElementById('pass').value;
if (!(/(?=.{8,16})(?=.*?[^\w\s])(?=.*?[0-9])(?=.*?[A-Z]).*?[a-z].*/.test(valor))) {
document.getElementById('pass').style.backgroundColor = "red";
} else {
document.getElementById('pass').style.backgroundColor = "#adff2f";
}
}
Regular expressions are not a panacea. It's not too hard to do it, mixing with regular code:
function validatePassword(password) {
// First, check the length.
// Please see my comment on the question about maximum password lengths.
if(password.length < 8 || password.length > 16) return false;
// Next, check for alphabetic characters.
if(!/[A-Z]/i.match(password)) return false;
// Next, check for numbers.
if(!/\d/.match(password)) return false;
// Next, check for anything besides those.
if(!/[^A-Z\d]/i.match(password)) return false;
// If we're here, it's valid.
return true;
}
However, I'd look into something like zxcvbn, a password checker, which I think is a better password quality checker, checking things like common dictionary words after un-13375p3/-\kification and dealing with entropy decently. It is used, among others, by Dropbox. Try it here.
You need to anchor the match to the beginning of the string, and anchor the first lookahead to the end:
^(?=.{8,16}$)
Also, the last lookahead needs to be split in two:
(?=.*?[A-Z])(?=.*?[a-z])
Why don't you just test for the three character sets with regular expressions:
[A-Za-z0-9]+
Then count the length of the string to validate the length.
What about this range:
/[A-Za-z0-9$-/:-?{-~!"^_`\[\]]/
So you can check first
/[A-Za-z]+/
then
/\d+/
and finally
/[$-/:-?{-~!"^_`\[\]]+/
If it passes you can check the length.
You can see this link to see why the symbols work.