Do not allow special characters except the allowed characters javascript regex - javascript

I have the following javascript code for my password strength indicator:
if (password.match(/([!,#,#,$,%])/)
{
strength += 2
}
So what this do is if the password contains one of these allowed characters (!,#,#,$,%), it will add a value to the strength of indicator.
My problem is I also want to decrease the strength of the password indicator once other special characters are present on the password. For example: ^,`,~,<,>
To remove confusion, basically I don't want any other special characters except the ones that is present above (!,#,#,$,%). So I did it hard coded, writing all special characters that I don't want.
I tried using this:
if (password.match(/([^,`,~,<,>])/)
{
strength -= 2
}
But I also don't want to include ", ' and , but then if I include them on my if condition, it will throw me an error saying syntax error on regular expression. I understand this because i know " represents a string which must be closed. Can I do something about it? Thanks in advance!

You don't need to separate your individual characters by commas, nor do you need to wrap the only term in brackets.
This should work:
/[`^~<>,"']/
note the carat (^ is not at the front, this has a special meaning when placed at the start of the [] block)
Also you should use test() because you only want a boolean if-contains result
/[`^~<>,"']/.test(password)

What you want to do is escape each of ", ', and , using a \. The regex you're looking for is:
/([\^\`\~\<\,\>\"\'])/
I actually generated that using the JSVerbalExpressions library. I highly recommend you check it out! To show you how awesome it is, the code to generate the above regex is:
var tester = VerEx()
.anyOf("^,`'\"~<>");
console.log(tester); // /([\^\`\~\<\,\>\"\'])/

Include these special characters in square brackets without commas and see if it works.
You can try it out here - http://jsfiddle.net/BCn7h/
Eg :
if (password.match(/["',]/)
{
strength -= 2
}

Related

Regex in Google Apps Script practical issue. Forms doesn't read regex as it should

I hope its just something i'm not doing right.
I've been using a simple script to create a form out of a spreadsheet. The script seems to be working fine. The output form is going to get some inputs from third parties so i can analyze them in my consulting activity.
Creating the form was not a big deal, the structure is good to go. However, after having the form creator script working, i've started working on its validations, and that's where i'm stuck at.
For text validations, i will need to use specific Regexes. Many of the inputs my clients need to give me are going to be places' and/or people's names, therefore, i should only allow them usign A-Z, single spaces, apostrophes and dashes.
My resulting regexes are:
//Regex allowing a **single name** with the first letter capitalized and the occasional use of "apostrophes" or "dashes".
const reg1stName = /^[A-Z]([a-z\'\-])+/
//Should allow (a single name/surname) like Paul, D'urso, Mac'arthur, Saint-Germaine ecc.
//Regex allowing **composite names and places names** with the first letter capitalized and the occasional use of "apostrophes" or "dashes". It must avoid double spaces, however.
const regNamesPlaces = /^[^\s]([A-Z]|[a-z]|\b[\'\- ])+[^\s]$/
//This should allow (names/surnames/places' names) like Giulius Ceasar, Joanne D'arc, Cosimo de'Medici, Cosimo de Medici, Jean-jacques Rousseau, Firenze, Friuli Venezia-giulia, L'aquila ecc.
Further in the script, these Regexes are called as validation pattern for the forms text items, in accordance with each each case.
//Validation for single names
var val1stName = FormApp.createTextValidation()
.setHelpText("Only the person First Name Here! Use only (A-Z), a single apostrophe (') or a single dash (-).")
.requireTextMatchesPattern(reg1stName)
.build();
//Validation for composite names and places names
var valNamesPlaces = FormApp.createTextValidation()
.setHelpText(("Careful with double spaces, ok? Use only (A-Z), a single apostrophe (') or a single dash (-)."))
.requireTextMatchesPattern(regNamesPlaces)
.build();
Further yet, i have a "for" loop that creates the form based on the spreadsheets fields. Up to this point, things are working just fine.
for(var i=0;i<numberRows;i++){
var questionType = data[i][0];
if (questionType==''){
continue;
}
else if(questionType=='TEXTNamesPlaces'){
form.addTextItem()
.setTitle(data[i][1])
.setHelpText(data[i][2])
.setValidation(valNamesPlaces)
.setRequired(false);
}
else if(questionType=='TEXT1stName'){
form.addTextItem()
.setTitle(data[i][1])
.setHelpText(data[i][2])
.setValidation(val1stName)
.setRequired(false);
}
The problem is when i run the script and test the resulting form.
Both validations types get imported just fine (as can be seen in the form's edit mode), but when testing it in preview mode i get an error, as if the Regex wasn't matching (sry the error message is in portuguese, i forgot to translate them as i did with the code up there):
A screenshot of the form in edit mode
A screeshot of the form in preview mode
However, if i manually remove the bars out of this regex "//" it starts working!
A screenshot of the form in edit mode, Regex without bars
A screenshot of the form in preview mode, Regex without bars
What am i doing wrong? I'm no professional dev but in my understanding, it makes no sense to write a Regex without bars.
If this is some Gforms pattern of reading regexes, i still need all of this to be read by the Apps script that creates this form after all. If i even try to pass the regex without the bars there, the script will not be able to read it.
const reg1stName = ^[A-Z]([a-z\'])+
const regNamesPlaces = ^[^\s]([A-Z]|[a-z]|\b[\'\- ])+[^\s]$
//Can't even be saved. Returns: SyntaxError: Unexpected token '^' (line 29, file "Code.gs")
Passing manually all the validations is not an option. Can anybody help me?
Thanks so much
This
/^[A-Z]([a-z\'\-])+/
will not work because the parser is trying to match your / as a string literal.
This
^[A-Z]([a-z\'\-])+
also will not work, because if the name is hyphenated, you will only match up to the hyphen. This will match the 'Some-' in 'Some-Name', for example. Also, perhaps you want a name like 'Saint John' to pass also?
I recommend the following :)
^[A-Z][a-z]*[-\.' ]?[A-Z]?[a-z]*
^ anchors to the start of the string
[A-Z] matches exactly 1 capital letter
[a-z]* matches zero or more lowercase letters (this enables you to match a name like D'Urso)
[-\.' ]? matches zero or 1 instances of - (hyphen), . (period), ' (apostrophe) or a single space (the . (period) needs to be escaped with a backslash because . is special to regex)
[A-Z]? matches zero or 1 capital letter (in case there's a second capital in the name, like D'Urso, St John, Saint-Germaine)

Javascript string validation. How to write a character only once in string and only in the start?

I am writing validation for phone numbers. I need to allow users to write + character only in the begining of input field and prevent users from writing it later in the field.
In other words:
+11111111 - right,
111111111 - right,
+111+111+ - false,
1111+111+ - false
The problem is that I need to perform validation while typing. As result I cannot analyse whole string after submision, thus it is not possible to fetch the position of + character because 'keyup' always returns 0.
I have tryed many approaches, this is one of them:
$('#signup-form').find('input[name="phone"]').on('keyup', function(e) {
// prevent from typing letters
$(this).val($(this).val().replace(/[^\d.+]/g, ''));
var textVal = $(this).val();
// check if + character occurs
if(textVal === '+'){
// remove + from occurring twice
// check if + character is not the first
if(textVal.indexOf('+') > 0){
var newValRem = textVal.replace(/\+/, '');
$(this).val(newValRem);
}
}
});
When I am trying to replace + character with empty string then it is replaced only once which is not enough, because user might type it a cople of times by mistake.
Here is the link to the fiddle: https://jsfiddle.net/johannesMt/rghLowxq/6/
Please give me any hint in this situation. Thanks!
To help you with the current code fix (#Thomas Mauduit-Blin is right that there are a lot more to do here than just allow plus symbol at the beginning only), you may remove any plus symbols that are preceded with any character. Just capture that character and restore with a backreference in the replacement pattern:
$(this).val($(this).val().replace(/[^\d.+]|(.)\++/g, '$1'));
See the updated fiddle and the regex demo.
The pattern is updated with a (.)\++ alternative. (.) captures any character but a newline into Group 1 that is followed with one or more plus symbols, and the contents of Group 1 is placed back during the replacement with the help of $1 backreference.
For better validation Why don't you use Jquery maskedinput library which will do lots of additional task for you without over head for other purpose also
$("#phone").mask("+999-999-9999");
$("#phone").mask("+9999-999-9999");
$("#phone").mask("+99999999999");
If you want to do the validation on your own, you must use a regex.
But, as described in another related thread here:
don't use a regular expression to validate complex real-world data like phone numbers or URLs. Use a specialized library.
You must let the user enter an invalid phone number, and perform the check later, or on form submit and/or on server side for example. Here, you want to take care of the "+" character, but there are lot's of other stuff to do to have a trustable validation.
If your textVal has a +, indexOf will only check for the first occurence. You need to ensure that first character is not checked by indexOf. So use substring to take out first character from the equation.
Simply replace
if(textVal.indexOf('+') > 0){
with
if(textVal.substring(1).indexOf('+') > -1){
Demo

JavaScript regex valid name

I want to make a JavaScript regular expression that checks for valid names.
minimum 2 chars (space can't count)
space en some special chars allowed (éàëä...)
I know how to write some seperatly but not combined.
If I use /^([A-Za-z éàë]{2,40})$/, the user could input 2 spaces as a name
If I use /^([A-Za-z]{2,40}[ éàë]{0,40})$/, the user must use 2 letters first and after using space or special char, can't use letters again.
Searched around a bit, but hard to formulate search string for my problem. Any ideas?
Please, please pretty please, don't do this. You will only end up upsetting people by telling them their name is not valid. Several examples of surnames that would be rejected by your scheme: O'Neill, Sørensen, Юдович, 李. Trying to cover all these cases and more is doomed to failure.
Just do something like this:
strip leading and trailing blanks
collapse consecutive blanks into one space
check if the result is not empty
In JavaScript, that would look like:
name = name.replace(/^\s+/, "").replace(/\s+$/, "").replace(/\s+/, " ");
if (name == "") {
// show error
} else {
// valid: maybe put trimmed name back into form
}
Most solutions don't consider the many different names there might be. There can be names with only two character like Al or Bo or someone that writes his name like F. Middlename Lastname.
This RegExp will validate most names but you can optimize it to whatever you want:
/^[a-z\u00C0-\u02AB'´`]+\.?\s([a-z\u00C0-\u02AB'´`]+\.?\s?)+$/i
This will allow:
Li Huang Wu
Cevahir Özgür
Yiğit Aydın
Finlay Þunor Boivin
Josué Mikko Norris
Tatiana Zlata Zdravkov
Ariadna Eliisabet O'Taidhg
sergej lisette rijnders
BRIANA NORMINA HAUPT
BihOtZ AmON PavLOv
Eoghan Murdo Stanek
Filimena J. Van Der Veen
D. Blair Wallace
But will not allow:
Shirley24
66Bryant Hunt88
http://stackoverflow.com
laoise_ibtihaj
hippolyte#example.com
Cy4n 4ur0r4 Blyth3 3ll1
Justisne
Danny
If the name needs to be capitalized, uppercase, lowercase, trimmed or single spaced, that's a task a formatter should do, not the user.
I would like to propose a RegEx that would match all latin based languages with their special characters:
/\A([ áàíóúéëöüñÄĞİŞȘØøğışÐÝÞðýþA-Za-z-']*)\z/
P.S. I've included all characters I could find, but please feel free to edit the answer in case I've missed any.
Why not
var reg= /^([A-Za-z]{2}[ éàëA-Za-z]*)$/;
2 letters, then as many spaces, letters or special characters as you want.
I wouldn't allow spaces in usernames though - it's begging for trouble when you have usernames like
ab ba
who's going to remember how many spaces they used?
You could do this:
/^([A-Za-zéàë]{2,40} ?)+$/
2-40 characters, and then optionally a space, repeated at least once. This will allow a space at the end, but you could trim it off separately.
After 'trim' the input value, The following will math your request only for Latin surnames.
rn = new RegExp("([\w\u00C0-\u02AB']+ ?)+","gi");
m = ln.match(rn);
valid = (m && m.length)? true: false;
Note that I am using '+', instead of '{2,}', that is because some surnames uses just one letter in a separated word like "Ortega y Gasset"
You can see I am not using RegExp.test, this is because that method don't work properly (I don't know why, but it has a high fail-rate, you may see it here:.
In my country, people from non-latin-language countries usually do some translation of their names so the previous RegExp would be enough. However, if you attempt to match any surname in the world, you may add more range of \u#### characters, avoiding to include symbols, numbers or other type. Or perhaps the xregexp library may help you.
And, please, do not forget to test the input in server side, and escaping it before using it in the sql sentences (if you have them)

Basic Regex to remove any space

I'm looking for a basic regex that removes any space. I want to use it for ZIP code.
Some people insert space after, before or in between the ZIP code.
I'm using /^\d{5}$/ now. I want to expand it to include space removal.
How can this be improved?
(I'm considering you want to remove spaces in your string, not verifying if it is valid even with spaces)
You can substitute one or more spaces (globally)
/\s+/g
by nothing.
zip.replace(/\s+/g, "");
Example in my browser's JS console:
> " 02 1 3 4".replace(/\s+/g, "");
"02134"
Here's a regex you can use instead of your current one to ignore any and all spaces.
/^(\s*\d){5}\s*$/
If you're sanitizing a form input or something, it's probably easiest to use:
zip = zip.replace(/\D/g,'');
you can then validate without a regex, just use the .length property on String.
if(zip.length != 5) alert('failed!');

find regex for validating terms (keyword) input

unfortunately i'm poor in regex! can you guide me to write a regex in javascript which can determine my terms input box. a user should input terms with this format:
#(all alphanumeric chars + blank + dash + quotation )
for example:
#keyword1#key word2#keyword3#key-word4#key'word5
and these inputs should be illegal:
#####
##keyword1#key2#
# #keyword
#!%^&
As you wrote a term is specified by:
/#[a-zA-Z0-9 '-]+/
Repeat that pattern, and force it to contain the start and end of the string with ^ and $.
/^(#[a-zA-Z0-9 '-]+)+$/
/#[a-zA-Z0-9][a-zA-Z0-9 '-]+/
When you said "# #keyword" should be invalid, I've assumed you mean "# " should be invalid and "#keyword" should be extracted from that string. The first 'box' means a keyword will always begin with a lowercase letter, uppercase letter, or number. If thats too restrictive and you want to allow for example "#-keyword", just add dash in before the first close-square-bracket, like so:
/#[a-zA-Z0-9-][a-zA-Z0-9 '-]+/
And to return an array of results in javascript, apply it to the string using the "global" modifier ('g' after the second slash):
arrayOfKeywords = keywordString.match(/#[a-zA-Z0-9-][a-zA-Z0-9 '-]+/g);
You may wish to see this code at my test page. Regular-expressions.info is a useful site to learn more about regular expressions. They also have an interactive page to test regexes on, which can be useful when playing around.

Categories

Resources