Javascript regex expressions - javascript

I need to validate a username in Javascript where only the patterns below can pass:
ABC-DE-0001
XEG-SS-21626
FK1S-DAD-51345
Mine is currently using ^[A-Z]{3}[\- ]?[A-Z]{2}[\- ]?[0-9]{4}$.
Are there any improvements to validate all above patterns in one string?
var v = document.getElementById('<%=txtCode.ClientID%>').value;
var patternForID = /^[A-Z]{3}[\- ]?[A-Z]{2}[\- ]?[0-9]{4}$/;
if (patternForID.test(v) == '') {
sender.innerHTML = "Please enter Valid Remeasurement Code";
args.IsValid = false; // field is empty
}

The following regular expression matches all three of your examples:
^([A-Z]{3}|[A-Z0-9]{4})-[A-Z]{2,3}-[0-9]{4,5}$
It's hard to tell exactly what your requirements are from those examples, but here's what the regex above matches.
([A-Z]{3}|[A-Z0-9]{4}) - Either three capital letters or any mix of 4 characters from capital letters and numbers.
[A-Z]{2,3} - Two or three capital letters.
[0-9]{4,5} - Four or five digits.
I assumed that - was your only legal separator, so I made it a literal - in the regex. If your separator really can be either a space or a -, change it back to [- ]. Also, adding a ? after the separator makes it optional, which doesn't seem to fit your examples. Naturally, you need to put it back if the separators are optional.
See it work in RegexPal with your examples.

Related

Regular Expression (regex, regexp) for username

Actual Code
Code Instructions
(Update): I added the instructions and code as images instead. I tried the suggestions and they did not go through. (Update)
This is my first ever question on here. Been using stack for advice but im stumped this time. I am new to regular expressions and am stuck on this assignment.
The question is as follows:
"write a regex test such that...
Only a username that has alphanumeric characters (lower and upper case letters
Numbers allowed only - (no spaces, no underscores)
Has at minimum 2 characters
Has a number as the final character (such as 'Jason1') is accepted via the form
We are working with this code here...
function validate() {
let inputStr = document.getElementById("username").value;
// const myReg = // Uncomment this line and add your regular expression literal here
if (myReg.test(inputStr))
alert("Username accepted");
else
alert("Username must contain only alphanumeric characters, contain a mininum of two characters, and end with a digit.");
}
So we have to take out the Uncomment and hopefully it matches the myReg.test.
I tried my best by doing /^[a-z\d][5.12]$/i and /^[a-z\d+?]$/i
But i am completely off! How should it look like?
My solution would be this (regex101 link):
/[A-z0-9]+\d/
Let me explain.
You can use [] to create lists of allowed characters (as in, each [] will match a single character, but any one in the list). Usually, I would use \w, but this is equivalent to [A-Za-z0-9_], and the question stipulates no underscores (you can save space by doing A to z, since capitals are before lower-case in unicode).
{} is used to specify an amount of a character that must match. So, you could say a{3,6}, and that would mean that only between three and six as would match. You can omit the last index (a{3,}) to say at least this many matches, or between n and unlimited times. Using this, you can match "at least one" with {1,}. This is then shortened to the equivalent +.
Finally, we say that the regex must have a digit \d at the end.
The "minimum length of two" is covered by requiring at least one of any accepted character with a digit at the end. One plus one is two.
function validate() {
let inputStr = document.getElementById("username").value;
const myReg = /^[a-z0-9]{1,}[0-9]$/igm
if (myReg.test(inputStr))
alert("Username accepted");
else
alert("Username must contain only alphanumeric characters, contain a minimum of two characters, and end with a digit.");
}
This link will make you understand all the regex https://regex101.com/r/dX3hD4/240

Name Validation Using Regular Expressions

I'm using a regular expression in my code, to validate the name and send the form, I just need some help by using it.
The Name should start by a capital letter and could be from 2-3 words, and could be separated by an apostrophe, space or a dash such as :
Victor Hugo
Jeanne D'arc
Jean-Marc Ayrault
I tried starting it by a capital, using /^[A-z][a-z]/
But i don't know how to continue it to validate spaces and dashes and apostrophes.
/^[A-z][a-z]/
I don't know how to continue it, thank you for your help.
You can use this regex,
\b[A-Z][a-z]*(?:'[a-z]+)?(?:[ -][A-Z][a-z]*(?:'[a-z]+)?)*\b
Explanation:
\b[A-Z][a-z]* - Starts matching a word boundary and uppercase letter followed by zero or more lowercase letters
(?:'[a-z]+)? - Optionally followed by ' and some lowercase letters. If you want to repeat this more than once, change ? to * like if you really want to support names like D'arcd'arc which I doubt if you wanted which is why I kept it with ?
(?:[ -] - Starts another non-grouping pattern and starts matching either with a space or hyphen
[A-Z][a-z]*(?:'[a-z]+)?)* - Further matches the same structure as in start of regex and zero or more times.
\b - Stops after seeing a word boundary
Demo
You could try the code below:
I'd suggest playing about with https://regexr.com/ for this purpose, it's very handy!
I've added a isValidNameStrict which only accepts a limited number of characters in the name.
Modify the [a-z'] group as you see fit to add extra characters.
function isValidNameStrict(name) {
let regEx = /^([A-Z][a-z']*[\-\s]?){2,}$/;
return regEx.test(name);
}
function isValidName(name) {
let regEx = /^(?:[A-Z][^\s]*\s?){2}$/;
return regEx.test(name);
}
function testName(name) {
console.log(`'${name}' is ${isValidNameStrict(name) ? "valid": "not valid"}`);
}
testName("Victor Hugo");
testName("Jeanne D'arc");
testName("Jean-Marc Ayrault");
testName("The Rock");
testName("Victor hugo");
testName("");
testName("Ozymandias");

How can I create a regular expression that accepts at least one lowercase and one digit?

This expression must adhere to specific rules:
1.- Between 2 and 8 characters total.
2.- Start with uppercase.
3.- Contain both lowercase and digits.
The first and second should be easy, but I can't get the third one to work.
This is the expression I came up with
([A-Z]+[A-Za-z0-9]*){2,8}
But it returns incorrect responses. Regular expressions are far from my forte, and this is the first time I had to use them outside of class.
This is my code, if it helps
var expresion = /([A-Z]+[A-Za-z0-9]*){2,8}/;
var re = new RegExp(expresion);
var t = $('#code').val();
if (re.test(t)) {
console.log(t+' works');
} else {
console.log(t+' not working');
}
This should fit your literal requirements (however, as comments state, they don't really make sense):
^(?=.{2,8}$)(?=.*[0-9])(?=.*[a-z])[A-Z][a-zA-Z0-9]*$
First, you need to anchor your match with ^ (start of string) and $; otherwise you can just be picking up a matching substring, which will mess up your requirements.
Second, we use lookahead to validate several individual points: the string contains between 2 and 8 characters before it ends, the string contains a digit.
Third, we use the character classes to validate that it starts with an uppercase, and continues with a mix of uppercase, lowercase and digits.
EDIT: Forgot the lowercase requirement, thanks nnnnnn. And you are right, your version is better.
Use look aheads that comport to each condition:
/^(?=[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.{2,8}$)(.*)/m
Demo
(As stated in comments, your target pattern is a minimum of 3 characters with the other conditions...)

regex that checks that a string is between two lengths and has only letters and numbers

I'm trying to validate a username field in my form via client-side valdiation and I'm having some trouble.
I'm trying to use match them against regexs, which seems to work for my password strength/match. However when I try and change the regular expression to one that is suitable for usernames it doesn't work.
This is the regular expression that works, it checks to see if the length is at least 6 chars long.
var okRegex = new RegExp("(?=.{6,}).*", "g");
This is the other regular expression which does not work:
var okRegex = new RegExp("/^[a-z0-9_-]{3,16}$/");
How do I write a regex that performs username validation? (That it's of a certain length, has only letters and numbers)
You're mixing regex literals with the RegExp constructor. Use one or the other, but not both:
okRegex = new RegExp('^[a-z0-9_-]{3,16}$');
or
okRegex = /^[a-z0-9_-]{3,16}$/;
As #zzzzBow answered you are mixing up two ways of using regular expressions. Choose one or the other. Now, a break down:
^ Matches the beginning of the string (that means that the string must start with whatever follows).
[a-z0-9_-] Matches the charecters a-z, A-Z, digits 0-9 _ (underscore) and - (dash/hyphen).
{3,16} States that there must be 3-16 occurences from the above character class.
$ Matches the end of the string, so the can't be anything after the 16 characters above.
Hope that helps.

Javascript RegEx not returning false as expected

Not a big user of RegEx - never really understood them! However, I feel the best way to check input for a username field would be with one that only allows Letters (upper or lower), numbers and the _ character, and must start with a letter as per the site policy. The My RegEx and code is as such:
var theCheck = /[a-zA-Z]|\d|_$/g;
alert(theCheck.test(theUsername));
Despite trying with various combinations, everything is returning "true".
Can anyone help?
Your regex is saying "does theUsername contain a letter, digit, or end with underscore".
Try this instead:
var theCheck = /^[a-z]([a-z_\d]*)$/i; // the "i" is "ignore case"
This says "theUsername starts with a letter and only contains letters, digits, or underscores".
Note: I don't think you need the "g" here, that means "all matches". We just want to test the whole string.
How about something like this:
^([a-zA-Z][a-zA-Z0-9_]{3,})$
To explain the entire pattern:
^ = Makes sure that the first pattern in brackets is at the beginning
() = puts the entire pattern in a group in case you need to pull it out and not just validate
a-zA-Z0-9_ = matches your character allowances
$ = Makes sure that this must be the entire line
{3,} = Makes sure there are a minimum of 3 characters.
You can add a number after the comma for a character limit max
You could also use a +, which would merely enforce at least one character match the second pattern. A * would not enforce any lengths
Use this as your regex:
^[A-Za-z][a-zA-Z0-9_]*$

Categories

Resources