I am trying to find a method to validate a string, using a list of allowed characters only.
var valid = validate('This is my string!', 'abcdefghijklmnopqrstuvwxyz');
function validate(value, allowed_chars){
var reg = new RegExp('[' + allowed_chars + ']');
var valid = reg.test(value);
return valid;
}
In this case, I wish for the function to return false because it has an exclamation mark in the string and that hasn’t been put in the allowed characters. Any ideas?
Help is much appreciated, Thankyou!
I do not wish to use a loop to check each character.
Your regex matches only single character. Add the quantifier.
‘+’ means ‘one or more occurences of this’
You also want to test if this pattern matches the entire string. Add markers for beginning and end of line.
You might also want to add upper case letters and spaces to your regex. Use an online regex tester to debug your regular expressions.