Regex to extract login username - javascript

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

Related

Validating client-side data input using a pattern

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}

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 - regex to check if user write correct formated input

in my CLI users can specify what they want to use:
A user command can look like this:
include=name1,name2,name3
category=name1,name2
category=name1
In another words, a command always consists of 3 parts:
command name: can be just include or category
=: is in every command
name or names of things they want to use, split by ,
How can I test this to get always true but false on everything else.
I am really bad in regex but I tried something like this:
/\category|include=\w/.test(str);
to simply test, at least, the most easy alternative which would be category=name1 but without success.
Can someone help me with this?
You were on the right path. Here's a fixed regex:
/^(category|include)=\w+(,\w+)*$/.test(str);
Note:
the parens around the alternative parts
the + after the \w so that you can have several characters
the optional (,\w+)*
the start and end of string marks (^ and $) in order to check the whole string
You can use this regex for your requorement:
/^(category|include)=(\w+(?:,\w+)*)$/
RegEx Demo
\w+(?:,\w+)*) in the value part after = will allow 1 or more of comma separated words.

Javascript match eveything except given words

Im working on a node.js app, and im doing router matching.
I need to match all routes with all variables except the ones which begin with
"public , static , files or same words with added "/"
i know i could do it using an if statement before regexp, to check if those words are withing url, and if they are, skip regexp, but i dont want to add such nesting, and knowing how to do it using regexp will become in handy in the future anyways.
i know how to match anything except...some letters, ie ^[0-9] , but i cant use the same for words. I googled and found that lookahead could solve this, but... i cant get it to work.
In the end, id like to use something like this (in pseudo code)
where the .+ would match only if the pattern does not match any of the given words.
match(/^(?!public|static|files) .+ /gi)
edit 1:
The format of the url's would be something like this..with or without slashes.
/controller/action/4/var:something/
i want to make a regexp that matches this controller - action - id
pattern, but at the same time wouldnt match patterns like this
/public/images/4
or
static/files/somefile
in general, id like to know how to match a pattern, but only if it doesnt begin with given words.
e.g something like this...but it doesnt work
( match .+, but only if it doesnt contain the words mentioned before
/^(?!public|static|files).+ /gi)
Actually, I'm not having trouble with negative look-aheads. Something like this seems to work just fine, although it's not super extensible.
/^\/(?!public|static|files)([^\/]+)?\/?([^\/]+)?\/?([^\/]+)?\/?(.*)$/i
1st capture will be the controller, 2nd is the action, 3rd is the ID, and 4th is whatever is left.
See this jsfiddle

How to remove space and restrict special chars using jquery?

I am creating a signup form in my website. I want to implement some checkup with username, which are
username can't have any space,
username can't have any special characters other than dot (.) as gmail is doing in thier signup form.
I am using jQUERY in my app, can anyone tell me how to implement above listed two checkups using jquery ?? I remember these two main checkups for username please suggest if you knows any other?
Thanks
Have a look at the validation plug-in.
Whatever you do, validate the username at the server side too.
You can check that using javascript regex:
if ($('#username').val().match(/^(\w)+[\w\d\.]*/)) {
// everyting is ok
}else {
// something is wrong
}
First see here in another entry in SO, jquery-validate-how-to-add-a-rule-for-regular-expression-validation.
if you need other ideas try here for an example using PHP and an AJAX call using jQuery.
You can also check out this page for a another jQuery solution.
I tried out following jquery script by studying the links (this one) given by #Dror to check for wrong characters in username,
if (!$('#uname').val().match("^[a-z0-9'.\s]{1,50}$")) {
//not a correct username
}
Thanks
When I checked the answers, I saw that space is allowed. So I improve the regex for others that will read this question:
You need to do like this:
if (!$('#uname').val().match(/^[a-z0-9_-]{3,15}$/)) {
alert("Please, use standard characters.");
}
Description of regex:
^ -- Start of the line
[a-z0-9_-] -- Match characters and symbols in the list, a-z, 0-9,
underscore, hyphen
{3,15} -- Length at least 3 characters and maximum length of 15
$ -- End of the line

Categories

Resources