Regular expression for name field in javascript validation - Stack Overflow
formvalidation.io - Validations for Password and First name using JavaScript - Stack Overflow
javascript - How to validate a first name via regex? - Stack Overflow
visualforce - How to validate First Name and Last Name in one input textbox using javascript? - Salesforce Stack Exchange
Videos
You can use pattern and inbuilt validation of HTML form
[^\d]+- To allow only characters except digits[\dA-Za-z]{8,}- To make sure only digits, and alphabets are allowed and atleast 8 characters
<body>
<form validate>
<label for="">First Name</label>
<input type="text" id="fname" pattern="[^\d]+" required><br>
<label for="">Last Name</label>
<input type="text" id="lname"><br>
<label for="">Email</label>
<input type="email" id="email" required><br>
<label for="">Password</label>
<input type="password" id="password" pattern="[\dA-Za-z]{8,}" required><br>
<button type="submit">Claim Your Free Trail</button>
<p>You Are Agreeing to Our <a href="#">Terms & Condition</a></p>
</form>
</body>
Password validation
We use the following regular expression to ensure the password contains only letters and numbers:
/[^A-Za-z0-9]+/g
- [^] : Matches anything NOT in the set
- A-Z : Characters in the range "A" to "Z"
- a-Z: Characters in the range "a" to "z"
- 0-9: Characters in the range "0" to "9"
- g: Global flag, allowing inerative search
So if the password contains non-letters and numbers, the regular expression return true.
And the whole password validation function as follow:
function isValidPassword(password) {
if (
typeof password !== "string" ||
password.length !== 8 ||
/[^A-Za-z0-9]+/g.test(password)
)
return false;
return true;
}
Firstname validation
We use the following regular expression to check if the password contains any numbers:
/[0-9]+/g
- [] : Matches anything IN the set
- 0-9: Characters in the range "0" to "9"
- g: Global flag, allowing inerative search
And the whole first name validation function as follow:
function isValidFirstname(firstname) {
if (
typeof firstname !== "string" ||
/[0-9]+/g.test(firstname)
) {
return false;
}
return true;
}
I have written this function for your purpose.
/**
* This function checks if first name
* is valid. Keep in mind this is
* not the proper solution. It will
* work only for names written in
* latin letters.
* @example
* isFirstNameValid('Ivan')
* will return true.
* isFirstNameValid('IvaN')
* will return false.
* @author Georgi Naumov
* [email protected] for contacts and
* suggestions
**/
const isFirstNameValid = (firstName) =>
/^[a-zA-z][a-z]+$/.test(firstName)
Edit: I have implemented a solution with unicode support for the people with a similar problem in the future. It supports Latin, Hebrew and Cyrillic. If you want to support another cultures you need to provide regexes for them inside cultures hash.
const isFirstNameValidWithUnicodeSupport = (firstName, culture = 'LATIN') => {
const cultures = {
HEBREW: /^[\u0590-\u05FF]{2,}$/,
CYRILLIC: /^[\u0410-\u042F\u0430-\u044F][\u0430-\u044F]+$/,
LATIN: /^[A-Za-z][a-z]+$/,
};
return cultures[culture].test(firstName);
}
This returns true because is valid name in latin
alphabet.
console.log(isFirstNameValidWithUnicodeSupport('Ivan'));
This returns true because is valid name in cyrillic
alphabet.
console.log(isFirstNameValidWithUnicodeSupport('Иван', 'CYRILLIC'));
This returns false because is valid name in cyrillic
alphabet but there is a space in the end.
console.log(isFirstNameValidWithUnicodeSupport('Иван ', 'CYRILLIC'));
This returns true because is valid name in hebrew
alphabet.
console.log(isFirstNameValidWithUnicodeSupport('אגרת', 'HEBREW'));
This returns false because is valid name in hebrew
but is whole name containing spaces. Not only first name.
console.log(isFirstNameValidWithUnicodeSupport('אגרת בת מחלת', 'HEBREW'));
Edit2: Probably better solution is xregexp library if you want to use library for that purpose. https://github.com/slevithan/xregexp
You can use regex for matching string characters.
let regex = /^[A-Za-z][a-z]+/g;
let name = "Mark";
let match = regex.exec(name);
if(match && match[0].length === name.length){
console.log(match[0]); // Mark
}
else{
console.log("Invalid name");
}
name = "mArk";
match = regex.exec(name);
if(match && match[0].length === name.length){
console.log(match[0]);
}
else{
console.log("Invalid name");
}
To learn more about regex.
Try Below Code
VF Code
<apex:inputtext value="{!name}" id="Name"/>
<apex:commandbutton onclick="validatenamevalue();" reRender="someId"/>
Javascript
function validatenamevalue(){
var name = document.getElementById('{!$Component.formId.Name}').value;
if(name == '' || name == null) {
alert('Please enter FirstName & LastName');
} else if((name.indexOf(' ') > 0 && name.indexOf(' ') == (name.length)-1) || !(name.indexOf(' ') > 0)) {
alert('Please Enter Last Name');
}
}
You can refer the following link and modify your code accordingly - How to write Javascript validation for Visualforce page
You can use javascript test() method to validate name field. The test() method tests for a match in a string.
/^[A-Za-z\s]+$/.test(x) //returns true if matched, vaidates for a-z and A-Z and white space
or
/^[A-Za-z ]+$/.test(x)
If you are building something for modern browsers, there is something very pleasurable in HTML5:
<input id="username" name="name" type="text" pattern="[a-zA-Z]{5,}" title="Minimum 5 letters" required />
Reference: HTML5 forms input types
Update 2017/01/17:
Old browsers are quite weak on the market shares nowadays. This is a good practice to use HTML5 features instead of compatibility scripts.
Don't forget about names like:
- Mathias d'Arras
- Martin Luther King, Jr.
- Hector Sausage-Hausen
This should do the trick for most things:
/^[a-z ,.'-]+$/i
OR Support international names with super sweet unicode:
/^[a-zA-ZàáâäãåąčćęèéêëėįìíîïłńòóôöõøùúûüųūÿýżźñçčšžæÀÁÂÄÃÅĄĆČĖĘÈÉÊËÌÍÎÏĮŁŃÒÓÔÖÕØÙÚÛÜŲŪŸÝŻŹÑßÇŒÆČŠŽ∂ð ,.'-]+$/u
You make false assumptions on the format of first and last name. It is probably better not to validate the name at all, apart from checking that it is empty.
The code you have looks fine, aside from the inconsistent variable reference (see the comment by Josh Purvis).
The following regex is fine for your first name spec:
var nameRegex = /^[a-zA-Z\-]+$/;
Adding digits for your username check is straightforward:
var usernameRegex = /^[a-zA-Z0-9]+$/;
Note: There are many ways to write regular expressions. I've chosen to provide a version that matches what you started with. I encourage you to work through this Regular Expression Tutorial
Here's the validation function I came up with, tailor it for your own use-cases:
function isUserNameValid(username) {
/*
Usernames can only have:
- Lowercase Letters (a-z)
- Numbers (0-9)
- Dots (.)
- Underscores (_)
*/
const res = /^[a-z0-9_\.]+$/.exec(username);
const valid = !!res;
return valid;
}
Does ^a-z*( a-z*)+$ work for you?
[a-z] ensures that a name always starts with a letter, then [-']?[a-z]+ allows for a seperating character as long as it's followed by at least another letter. * allows for any number of these parts.
The second half, ( a-z*) matches a space followed by another name of the same pattern. + makes sure at least one additional name is present, but allows for more. ({1,2} could be used if you want to allow only two or three part names.
Simpler version
/^([\w]{3,})+\s+([\w\s]{3,})+$/i
([\w]{3,}) the first name should contain only letters and of length 3 or more
+\s the first name should be followed by a space
+([\w\s]{3,})+ the second name should contain only letters of length 3 or more and can be followed by other names or not
/i ignores the case of the letters. Can be uppercase or lowercase letters