Using regex in cloud functions - javascript

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

Related

Replace all instances of character in string in typescript?

I'm trying to replace all full stops in an email with an x character - for example "my.email#email.com" would become "myxemail#emailxcom". Email is set to a string.
My problem is it's not replacing just full stops, it's replacing every character, so I just get a string of x's.
I can get it working with just one full stop, so I'm assuming I'm wrong on the global instance part. Here's my code:
let re = ".";
let new = email.replace(/re/gi, "x");
I've also tried
re = /./gi;
new = email.replace(re, "x");
If anyone can shed any light I'd really appreciate it, I've been stuck on this for so long and can't seem to figure out where I'm going wrong.
** Edit: Whoops, my new variable was actually called newemail, keyword new wasn't causing the issue!
Your second example is the closest. The first problem is your variable name, new, which happens to be one of JavaScript's reserved keywords (and is instead used to construct objects, like new RegExp or new Set). This means that your program will throw a Syntax Error.
Also, since the dot (.) is a special character inside regex grammar, you should escape it as \.. Otherwise you would end up with result == "xxxxxxxxxxxxxxxxxx", which is undesirable.
let email = "my.email#email.com"
let re = /\./gi;
let result = email.replace(re, "x");
console.log(result)
You can try split() and join() method that was work for me. (For normal string text)
It was short and simple to implement and understand.
Below is an example.
let email = "my.email#email.com";
email.split('.').join('x');
So, it will replace all your . with x. So, after the above example, email variable will have value myxemail#gmailxcom
You may just use replaceAll() String function, described here:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll
If you are getting
Property 'replaceAll' does not exist on type 'string'
error - go to tsconfig.json and within "lib" change or add "es2021".
Like this:
More info here: Property 'replaceAll' does not exist on type 'string'

Jquery validate free emails using validator

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,

Javascript: test whether a string is a regular expression

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

Regex validation rules

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.

What are these javascript syntax called? "/^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/"

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

Categories

Resources