Name Validation Using Regular Expressions - javascript

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");

Related

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...)

How to apply part of this regular expression to all alternatives?

I have to write a regex that contains either the words “wind”, “temp”, or “press” followed by a non-digit.
So far I have:
var regex = /wind|temp|press[^0-9]{0,}/;
This doesn’t work because the [^0-9]{0,} is with “press”. How would I separate them so that all the words would be read followed by a non digit?
Just use a (non-capturing) group:
var regex = /(?:wind|temp|press)[^0-9]{0,}/;
All you need is a none capturing group to separates those words from the rest of your pattern. Use this pattern:
/(?:wind|temp|press)\D*/
By the way {0,} is the same as * in this case. Also if being a non-digit character is mandatory, you probable want to use + instead. (I mean if one of those words must be followed by at least one or more non-digit character, then use +)
Online Demo

If Statement with .match(regex) in javascript not picking up spaces

Hi guys I'm trying to check if user input string contains a space. I'm using http://regexr.com/ to check if my regular expression is correct. FYI new to regex. Seems to be correct.
But it doesn't work, the value still gets returned even if there is a space. is there something wrong with my if statement or am I missing how regex works.
var regex = /([ ])\w+/g;
if (nameInput.match(regex)||realmInput.match(regex)) {
alert('spaces not allowed');
} else {
//do something else
}
Thanks in Advance
This regex /([ ])\w+/g will match any string which contain a space followed by any number of "word characters". This won't catch, for example, a space at the end of the string, not followed by anything.
Try using /\s+/g instead. It will match any occurrence of at least one space (including tabs).
Update:
If you wish to match only a single space this will do the trick: / /g. There's no real need for the brackets and parenthesis, and since one space is enough even the g flag is kind of obsolete, it could have simply been / /.
Your current regex doesn't match 'abc '(a word with space character at the end) . If you want to make sure, you can trim you input before check :).
You can check here https://regex101.com/
The right regex for matching only white space is
/([ ])/g

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_]*$

Regex to check only capital letters, two special characters (& and Ñ) & without any space between

I am using below code snippet to validate my input string with: only capital letters, numbers and two special characters (those are & and Ñ) & without any space between.
var validpattern = new RegExp('[^A-Z0-9\d&Ñ]');
if (enteredID.match(validpattern))
isvalidChars = true;
else
isvalidChars = false;
Test 1: "XAXX0101%&&$#" should fail i.e isvalidChars = false; (as it contains invalid characters like %$#.
Test 2: "XAXX0101&Ñ3Ñ&" should pass.
Test 3: "XA 87B" should fail as it contains space in between
The above code is not working, Can any one help me rectifying the above regex.
This is happening because you have a negation(^) inside the character class.
What you want is: ^[A-Z0-9&Ñ]+$ or ^[A-Z\d&Ñ]+$
Changes made:
[0-9] is same as \d. So use
either of them, not both, although it's not incorrect to use both, it's redundant.
Added start anchor (^) and end
anchor($) to match the entire
string not part of it.
Added a quantifier +, as the
character class matches a single
character.
^[A-Z\d&Ñ]+$
0-9 not required.
if you want valid patterns, then you should remove the ^ in the character range.
[A-Z0-9\d&Ñ]
Using jquery we could achieve the same in one line:
$('#txtId').alphanumeric({ allow: " &Ñ" });
Using regex (as pointed by codaddict) we can achieve the same by
var validpattern = new RegExp('^[A-Z0-9&Ñ]+$');
Thanks everyone for the precious response added.

Categories

Resources