I have a user-created string which is to be used as a regular expression. How can I test the validity of this string?
My first thought was to use a regular expression to test this, but, thinking about it, the regular expression syntax itself is not a regular language, so this doesn't work.
My second thought was to attempt to create a RegExp object using the string. However, the documentation does not mention what should happen when the string is an invalid regular expression.
Any other ideas?
Use try/catch to determine whether given string is able to create a valid RegExp object or not:
s = "(abc"; // invalid input regex string
valid = false;
try {
new RegExp(s);
valid = true; // reached here regex is valid
} catch(ex) {}
console.log(valid); // false
Related
I want to test a string that is from an input using a regular expression.
it is a quite simple regex: [0-9]{8}
The problem is that I keep getting an error.
The code:
const GETparam = req.query.kvk;
const KvK = GETparam.toString();
//Test if it is a valid KvK number [0-9]{8}
var KvKregex = new Regexp('[0-9]{8}');
if(KvKregex.test(KvK) != true){
res.status(405).send('KvK number provided was invalid');
return;
}
Explaination: If the input from the GET parameter(http://......?kvk=number), the kvk number, doesn't match the regex, it should return a 405. Else, the code should just keep running.
It says Regexp is not defined.
Do I need to include something? I can't find how to actually use a regular expression in a cloud function. How can I achieve this?
The Cloud Functions nodejs environment is just plain nodejs running JavaScript. Cloud Functions don't not change the way the language works.
You should use RegExp (note the capital E) instead of Regexp.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp
I used jquery validator for validation.I have 50 free emails like(gmail.com, yahoo.com) so I need validate it.I chose an array then stored all the emails within an array.Below see my code there you could see I used the regular expression.I passed a variable in regular expression but it doesn't work for me.It threw the error like this SyntaxError: invalid range in character class
My code
$.validator.addMethod('nofreeemail', function (value) {
var emails = ["gmail.com","yahoo.com","hotmail.com"]
$.each(emails,function(i, val){
console.log("email", val)
var regex = new RegExp("/^([\w-.]+#(?!"+val+")([\w-]+.)+[\w-]{2,4})?$/");
console.log("regex", regex)
return regex.test(value);
});
}, 'Free email addresses are not allowed.');
I will post an answer since it is not evident here what is going on, but the underlying reasons are quite common.
You are using a constructor notation to define the regex. It is a correct approach when you need to build a pattern dynamically using a variable. However, a literal backslash must be written as "\\". All single backslashes are removed. Thus, you get an error since [\w-.] turns into [w-.] and it is an invalid character class. Also, the regex delimiters (those /..../ around the pattern) should never be used in the constructor notation unless you really need to match a string enclosed with /.
Besides, your emails contain non-word chars, and you need to escape them.
Use
var regex = new RegExp("^([\\w-.]+#(?!"+val.replace(/[-\/\\^$*+?.()|[\]{}]/g,'\\$&')+")([\\w-]+\\.)+[\\w-]{2,4})?$");
I also believe the dot in ([\w-]+.)+ must be escaped, it is supposed to match a literal dot,
I'm writing a database backup function as part of my school project.
I need to write a regex rule so the database backup name can only contain legal characters.
By 'legal' I mean a string that doesn't contain ANY symbols or spaces. Only letters from the alphabet and numbers.
An example of a valid string would be '31Jan2012' or '63927jkdfjsdbjk623' or 'hello123backup'.
Here's my JS code so far:
// Check if the input box contains the charactes a-z, A-Z ,or 0-9 with a regular expression.
function checkIfContainsNumbersOrCharacters(elem, errorMessage){
var regexRule = new RegExp("^[\w]+$");
if(regexRule.test( $(elem).val() ) ){
return true;
}else{
alert(errorMessage);
return false;
}
}
//call the function
checkIfContainsNumbersOrCharacters("#backup-name", "Input can only contain the characters a-z or 0-9.");
I've never really used regular expressions before though, however after a quick bit of googling i found this tool, from which I wrote the following regex rule:
^[\w]+$
^ = start of string
[/w] = a-z/A-Z/0-9
'+' = characters after the string.
When running my function, the whatever string I input seems to return false :( is my code wrong? or am I not using regex rules correctly?
The problem here is, that when writing \w inside a string, you escape the w, and the resulting regular expression looks like this: ^[w]+$, containing the w as a literal character. When creating a regular expression with a string argument passed to the RegExp constructor, you need to escape the backslash, like so: new RegExp("^[\\w]+$"), which will create the regex you want.
There is a way to avoid that, using the shorthand notation provided by JavaScript: var regex = /^[\w]+$/; which does not need any extra escaping.
It can be simpler. This works:
function checkValid(name) {
return /^\w+$/.test(name);
}
/^\w+$/ is the literal notation for new RegExp(). Since the .test function returns a boolean, you only need to return its result. This also reads better than new RegExp("^\\w+$"), and you're less likely to goof up (thanks #x3ro for pointing out the need for two backslashes in strings).
The \w is a synonym for [[:alnum:]], which matches a single character of the alnum class. Note that using character classes means that you may match characters that are not part of the ASCII character encoding, which may or may not be what you want. If what you really intend to match is [0-9A-Za-z], then that's what you should use.
When you declare the regex as a string parameter to the RegExp constructor, you need to escape it. Both
var regexRule = new RegExp("^[\\w]+$");
...and...
var regexRule = new RegExp(/^[\w]+$/);
will work.
Keep in mind though, that client side validation for database data will never be enough, as the validation is easily bypassed by disabling javascript in the browser, and invalid/malicious data can reach your DB. You need to validate the data on the server side, but preventing the request with invalid data, but validating client side is good practice.
This is the official spec: http://dev.mysql.com/doc/refman/5.0/en/identifiers.html but it's not very easily converted to a regular expression. Just a regular expression won't do it as there are also reserved words.
Why not just put it in the query (don't forget to escape it properly) and let MySQL give you an error? There might for instance be a bug in the MySQL version you're using, and even though your check is correct, MySQL might still refuse.
I have this regex on Javascript :
var myString="aaa#aaa.com";
var mailValidator = new RegExp("\w+([-+.]\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*");
if (!mailValidator.test(myString))
{
alert("incorrect");
}
but it shouldn't alert "incorrect" with aaa#aaa.com.
It should return "incorrect" for aaaaaa.com instead (as example).
Where am I wrong?
When you create a regex from a string, you have to take into account the fact that the parser will strip out backslashes from the string before it has a chance to be parsed as a regex.
Thus, by the time the RegExp() constructor gets to work, all the \w tokens have already been changed to just plain "w" in the string constant. You can either double the backslashes so the string parse will leave just one, or you can use the native regex constant syntax instead.
It works if you do this:
var mailValidator = /\w+([-+.]\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*/;
What happens in yours is that you need to double escape the backslash because they're inside a string, like "\\w+([-+.]\\w+)*...etc
Here's a link that explains it (in the "How to Use The JavaScript RegExp Object" section).
Try var mailValidator = new RegExp("\\w+([-+.]\\w+)*#\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*");
I have the following code as part of my email validation script. I'd like to learn more about the variable reg but don't know how to find relevant information because I do not know what the syntax is called. Could someone direct me to the proper resource or tell me the name of this type of syntax?
function validate(form_id,email) {
var reg = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
var address = document.forms[form_id].elements[email].value;
if(reg.test(address) == false) {
alert('Invalid Email Address');
return false;
}
}
It's called a regular expression.
There are a lot of resources on regexes, and particularly about regexes in JS. Here is a guide that explains how to use them:
http://www.javascriptkit.com/javatutors/re.shtml
and a guide to the patterns themselves:
http://www.javascriptkit.com/javatutors/redev2.shtml
Check out the nice wikipedia article:
Regular Expressions
In computing, a regular expression,
also referred to as regex or regexp,
provides a concise and flexible means
for matching strings of text, such as
particular characters, words, or
patterns of characters. A regular
expression is written in a formal
language that can be interpreted by a
regular expression processor, a
program that either serves as a parser
generator or examines text and
identifies parts that match the
provided specification.
If you are worry about something, thats nothing to worry about. Thats called Regular Expression AKA Regex. What this script is doing in this code? It is matching/validating the user input to only accept email addresses which are well formatted.
test###test.com (invalid)
test#test.com (valid)
function check_email()
{
// /^[+a-zA-Z0-9]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/i this anather regular experession
var pattern = new RegExp(/^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/);
if (pattern.test($('#form_email').val()))
{
$('#email_error_message').hide();
}
else
{
$('#email_error_message').html('Invalid Email');
$('#email_error_message').show();
error_email = true;
}
}
This is a regular expression (regex). Find more information here: http://www.regular-expressions.info/javascript.html.
The expression to the right is called a regular expression.
You can get more info from : http://www.regular-expressions.info/javascript.html