Validating client-side data input using a pattern - javascript

I am currently working on a project whereby data can be added into a database via a website. Currently I have managed to configure it so that the form accepts title, postcode, vehicle reg and ID number.
Javascript validation is working fine for these entries, with the exception of ID number. All ID numbers are a specific format (2 numbers followed by a . followed by 4 numbers).
I cannot seem to work out how to define the pattern.
Due to the size of my code, I have not posted the full code here (all is validating except this ID validation), but I've provided a snip of the 'if' statement below which I'm trying to come up with.
if (inputElement.id == "wid") {
pattern = /^[a-zA-Z0-9 ]*$/;
feedback = "Only 2 numbers followed by a . followed by 4 numbers are
permitted";
I know that the pattern isn't correct here but I have searched for hours trying to locate some easy to explain guidance and cannot find anything which appears to be relevant.
Any thoughts would be appreciated.
Thank you

You can try out something like https://regex101.com/ to test you regexes, and see an explanation of it.
I think your pattern should be this: /^[0-9]{2}\.[0-9]{4}$/.
The first part ([0-9]{2}) makes sure that the id starts with 2 digits, then a dot \. (which must be escaped, because it means "every character" otherwise) and then 4 digits [0-9]{4}

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)

Is it possible to have an emoji-only text input?

I'm building an Ionic2 app and one of my text fields needs to be an emoji-only field.. to make my situation a little harder, the input field can only be 1 emoji long.
From what I know of emojis, some are considered 2 characters, and some are 1, which makes me wonder how I can force only 1 emoji length in a text input.
Is this possible? Essentially just a text field that only accepts 1 emoji..
Any feedback would be great. Thank you!
Since you haven't yet provided your own code I'm not going to answer your whole question.
You could start off by using a regular expression that only allows characters and then modify it using something like the emoji regex library provided below.
var val = "🐬";
if (val.match(/[^a-zA-Z]/g)) { // NOTE: will also match only characters
console.log(val);
} else {
console.log("Only characters allowed.")
}
You could also try a library like the following that's a regular expression to match all Emoji-only symbols as per the Unicode Standard. https://mths.be/emoji-regex
There's also a great article on Optimizing RegEx for Emoji.

Regex to extract login username

Currently, I had one Web chat project, I use socket.io to send and receive messages real time.
I need to get the login if user types.
I try to use regex but I'm a beginner within and the format can be multiples like:
My login is sayuri.mizuguchi
My login? So, sayuri.mizuguchi Okay?
The format from login is always firstname.lastname
In this case, all messages stay inside a parameter and this data is saved inside one variable but I really try use multiples regex for test and anything works.
Someone can help me, please?
Example:
console.log(data.usertyped); // My login is sayuri.mizuguchi
I need use like condition, like: input.text.find('\d{11}') that get 11 numbers within a condition even if the user types "My number is 11122233344" and I need the same to get login.
Thanks advance.
While trying to match a string in format of ----.---- where each - denotes a word character (a-z, A-Z, 0-9 or _) you have to work with \w meta-character which means all of it:
^\w+\.\w+$
Using ^ and $ anchors make sure regex should start to match from beginning of an input string to its end respectfully otherwise it should fail. Like in following cases:
#firstname.lastname
mohammad.hoss*ein
To add more characters into consideration you need to use character classes:
^[\w#-]+\.[\w#-]+$
Also you should know the least needed characters that ^\w+\.\w+$ expects is a word character in both sides of the period:
a.b

Email Validation RegEx username/local name length check not running

I've debugged for a few hours now and have hit a wall - regex has never been my strongsuit. I have been able to alter the following regex to restrict 255 characters for domain fine, however, in trying to restrict the local/username portion of an email address I'm running into issues implementing a 64 character limit. I've gone through regex101 replacing +s and *s and attempting to understand what each pass is doing - however, even when I add a check against all non-whitespace characters with a limit of 64 it seems like the other checks pass and take precedence - although I'm not sure. Below is my regex currently without any of the 64 character checks that I've broken it with:
var emailCheck = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.{0,1}([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))#((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]){1,255}([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]){1,255}([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.*$/i);
What I have so far can be seen at http://jsfiddle.net/mtqx0tz1/ , I've made other slight alterations (e.g. not allowing consecutive dots) but for the most part this regex comes from another stack post without the character limits.
Lastly, I'm aware this isn't the 'standard' so to speak and emails are checked server-side, however, I would like to be more safe than sorry...as well as work on some of my regex. Sorry if this question isn't worthy of an actual post - I'm just simply not seeing where in my passes {1,64} is failing. At this point I'm thinking about just sub-stringing the portion of the string up to the # sign and checking length that way...but it would be nice to include it in this statement since all the checks are done here to begin with.
I have used this regex validation and it works good.
The e-mail address is in the variable strIn
try
{
return Regex.IsMatch(strIn,
#"^(?("")("".+?(?<!\\)""#)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])#))" +
#"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-\w]*[0-9a-z]*\.)+[a-z0-9][\-a-z0-9]{0,22}[a-z0-9]))$",
RegexOptions.IgnoreCase, TimeSpan.FromMilliseconds(250));
}
catch (RegexMatchTimeoutException)
{
return false;
}

How to modify regex for phone numbers and accept only digits

I have this following regex method for the jquery validate plugin.
jQuery.validator.addMethod("phoneUS", function(phone_number, element) {
phone_number = phone_number.replace(/\s+/g, "");
return this.optional(element) || phone_number.length > 9 &&
phone_number.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/);
}, "Please specify a valid phone number");
Currently, its validating against phone numbers in this format : 203-123-1234
I need to change to validate like this: 2031231234
Does anyone have a quick and easy solution for me?
You can replace
phone_number.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/);
with this
phone_number.match(/\d{10}/);
\d means match any digit
and
{10} means 10 times
Getting rid of all those -? sequences is probably the quickest way - they mean zero or one - characters.
That will reduce it to:
/^(1)?(\([2-9]\d{2}\)|[2-9]\d{2})[2-9]\d{2}\d{4}$/
whih can be further simplified to:
/^1?(\([2-9]\d{2}\)|[2-9]\d{2})[2-9]\d{6}$/
If you also want to disallow the brackets around area codes, you can further simplify it to:
/^1?[2-9]\d{2}[2-9]\d{6}$/
(and, technically, it won't match the literal 203-123-1234 since the character immediately after that first - has to be 2 thru 9, so I'm assuming you were just talking about the format rather than the values there).
I think better approach would be changing the whole expression with simpler version, something like this:
/^[0-9]{10}$/
Edited, Note (see comments):
This is just a limited example of how to validate a format: 111-222-3333 vs 1112223333, not proper US phone number validation.
If you just want ten digits, then
phone_number.match(/\d{10}/)
will do it. If you want to match any of the other conditions in there (eg match both 1-2031231234 and 2031231234), you will need to add more.
As a side note, what you currently have doesn't match 203-123-1234 because the first digit after the first hyphen is a 1, and it is looking for 2-9 in that spot.
([0-9]{10}) this will match with 10 digit number.
You can use if you want to match all formats, including 203-123-1234 and 2031231234
EDIT : I'm no regex expert, but I added "1-" support
/^(?:1-?)?[(]?\d{3}[)]?\s?-?\s?\d{3}\s?-?\s?\d{4}$/
By the way, there's a really nice AIR tool for regex, it's called RegExr and you can get the desktop version here http://www.gskinner.com/RegExr/desktop/ or use the online version http://gskinner.com/RegExr/ . There's also a "community" section that contains a lot of useful working regex. That's where I took that one.

Categories

Resources