How to remove space and restrict special chars using jquery? - javascript

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

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)

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

RegEx for email to allow Empty spaces, vaild email address and multiple email addresses

I have this RegEx which I use for CC and BCC email fields
reg = /(^\s*$|^[a-zA-Z0-9._%+-]+#[a-zA-Z0-9.-]+\.(?:[a-zA-Z]{2}|com|org|net|edu|gov|mil|biz|info|mobi|name|aero|asia|jobs|museum)$)/;
This allows for the email field to be empty, or have a valid email address, otherwise it will error.
I would like to extend the RegEx to allow mutiple emails also e.g. a#a.com, b#b.com, c#c.com
I have tried adding [,;] to allow comma or semicolon seperated values, but i can't seem to get it to work.
Any one know if i'm on the right lines with [,;] and where I should be placing it?
Update: I've updated the RegEx to, so it doesn't look for gTLDs:
reg =
/(^\s*$|^[a-zA-Z0-9._%+-]+#[a-zA-Z0-9.-]+.[A-Za-z]{2,4}[,;]?)+$/;
thanks
If Alex K.'s comment about ASP.NET validation doesn't help, then I have a band-aid for you. I wouldn't consider this a proper answer, as there really isn't a way to get exactly the functionality that you're looking for without giving us all pre and post email special characters that can occur. You could use something like this that uses non-capture groups to help find matches. It's not 100% accurate, but it should work for most cases. One problem with it is that you're apt to capture garbage/non-desired results if it runs into stray # symbols.
regex tested by RegexBuddy 4.2.0:
(?m)(?:^|\s|\n|\t|\r|,|;|
)[^\n]*?#[^\n]*?\.[^\n]*?(?:$|;|\s|,)
Test strings used:
9som$emaIL#cm3Gks.qa1vv; 9som$emaIL#cm3Gks.qa1vv, 9som$emaIL#cm3Gks.qa1vv; 9som$emaIL#cms.com ;
dd.dd.ddwe.wscef_sed#_e23&&*^.dvcw

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!');

Categories

Resources