I am having a script which validates a user's name. When the user enters name without spaces then it works fine. If user enters name with spaces (name, surname, lastname etc) then it is not working. I am trying to capture 'space' character using \s but it is not working.
My script is:
var name=document.forms["newform"]["fullname"].value; //get the name from HTML form
var charpos = name.search("[^A-Za-z\s]");
if (name.length <= 0 || name.length>=50 || charpos >= 0)
{
alert('wrong.');
}
else
{
alert('correct');
}
Input1: AFGH
Output1: correct
Input2: ABCD EFGH
Output2: wrong
When Input2 is given, charpos gets the value '5'.
The string literal is swallowing the \.
You should use a regex literal:
name.search(/[^A-Za-z\s]/);
Related
I am making a Signup form.
In that, I have a username field that should not allow the characters -, space, ", ' but I can't get that to happen.
I tried:- Slice method, substring method, regex, remove and split method and join technique.
So code:
function username(event) {
text = document.getElementById('usname').value;
key = event.key;
if (key == ' ' || key == '"' || key == "'" || key == '-') {
setTimeout(() => {
let final = text.slice(0, -1);
document.getElementById('usname').value = final';
},0.005)
}
}
This was my best approach was this but it removed two characters at once and if we spam space and then type a character, we get a space in the text which is invalid.
You can use regular expression [Regex]
This regex will accept only alphabets and numbers , and remove special characters and spaces.
function username(event) {
text = document.getElementById('usname').value;
document.getElementById('usname').value = text.replace(/[^a-zA-Z0-9\w]/g, "");
}
<input type="text" onkeyup="username()" id="usname" />
EDIT
[^a-zA-Z0-9\w] is the same as [^\w] or just \W. All will allow , so
[^a-zA-Z0-9] or [\W] would be better. – MikeM
You are right my friend, this much better.
function username(event) {
text = document.getElementById('usname').value;
document.getElementById('usname').value = text.replace(/[\W_]/g, "");
}
<input type="text" onkeyup="username()" id="usname" />
EDIT
I don't want other symbols to be removed I just want these:- the dash(-), space, single and double quotes(',"). – Shaurya Shrimal
Add the symbols you want to remove in regex /[-'" ]/g
function username(event) {
text = document.getElementById('usname').value;
document.getElementById('usname').value = text.replace(/[-'" ]/g, "");
}
<input type="text" onkeyup="username()" id="usname" />
First of all, to give the best user experience to the user, you should inform the user with a hint text below the input box saying that these characters are not allowed.
It is recommended to have a validation on the input box, which will warn the user by highlighting the input box as red when the user inputs invalid characters, and not allowing to submit, rather than removing the characters from their entry without their knowledge.
For form validation, use a library like validator for detecting invalid characters. Example for validating username that should have only alpha numeric characters:
validator.isAlphanumeric('fooBar123'); //=> true
When I ask the user how do I check they only enter a string and up to 10 characters?
function setUserName() {
let myName = prompt('Please enter your name');
if (!myName|| myName === null||myName !== string.myName) {
setUserName();
} else {
localStorage.setItem('name', myName);}
}
}
Stuck in a loop.
You could use a regular expression and testing the length of the string:
if(!myName || myName.length > 10 || /[^A-Za-z]/g.test(myName)) {
//invalid input
}
It only allows letters uppercase and lowercase.
Welcome to the stack overflow.
The strings can be treated as an array, you have the length method on them, so performing a myName.length would return you a length of that string.
And if you want to check the string for the characters (assuming only alphabets in the English language), then you can do it with the regexp: /[^A-Za-z]/g.test(myName). For more details on regular expressions go here.
You can use string.length to find the length of the string:
let myName = prompt('Please enter your name');
if (myName.length == 0 && myName.length > 10){ //string has content and is bigger than 10 characters
setUserName();
}else{ //a string less than 10 characters
localStorage.setItem('name',myname);
}
Edit: forgot that prompt always returns a string
I have a string like this:
Francesco Renga <francesco_renga-001#gmail.com>
I need to extract only the email, i.e. francesco_renga-001#gmail.com.
How can I do this in nodejs/javascript in "elegant" way?
Using regex, if your string pattern is always Some text<email> or Some text<email>, Some text<email> <email> you can use this simple one <(.*?)>
Demo
Other solution
Use positive lookahead : [^<]+(?=>), here is a snippet and a demo
var text = "Francesco Renga <francesco_renga-001#gmail.com>, Marty McFly <mmcfly#gmail.com> Marty McFly <mmcfly#gmail.com> <mmcfly2#gmail.com>";
var re = /[^< ]+(?=>)/g;
text.match(re).forEach(function(email) {
console.log(email);
});
Explanation
[^<]+ match anything but a <between one and unlimited times
(?=>) followed by a >
Simple and does not require any group.
Here's a simple example showing how to use regex in JavaScript :
var string = "Francesco Renga <francesco_renga-001#gmail.com>"; // Your string containing
var regex = /<(.*)>/g; // The actual regex
var matches = regex.exec(string);
console.log(matches[1]);
Here's the decomposition of the regex /<(.*)>/ :
/ and / are mandatory to define a regex
< and > simply matches the two < and > in your string
() parenthesis "capture" what you're looking for. Here, they get the mail address inside.
.* : . means "any character", and * means "any number of times. Combined, it means "any character any number of times", and that is inside < and >, which correspond to the place where the mail is.
Here's a simple code showing how extract the unique list of emails address using JavaScript :
let emaillst = string .match(/([a-zA-Z0-9._+-]+#[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+)/gi);
if (emaillst === null) {
// no Email Address Found
} else {
const uniqueEmail = Array.from(new Set(emaillst));
const finaluniqueEmail = [];
for(let i=0; i<=uniqueEmail.length; i++){
let characterIs = String(uniqueEmail[i]).charAt(String(uniqueEmail[i]).length - 1)
if(characterIs==='.'){
finaluniqueEmail.push(String(uniqueEmail[i].slice(0, -1)))
}else{
finaluniqueEmail.push(uniqueEmail[i]);
}
}
emaillst = finaluniqueEmail.join('\n').toLowerCase();
console.log(matches[1]);
See the Live Demo of email address extractor online
Features
Get Unique Emails
Auto remove duplicate emails
convert upper case email address to lowercase
i have below string from which I have to extract username and ID.
This is a string which has a #[User Full Name](contact:1) data inside.
To get username and contact id from above string I am using this regex pattern.
var re = /\#\[(.*)\]\(contact\:(\d+)\)/;
text = text.replace(re,"username:$1 with ID: $2");
// result == username: User Full Name with ID: 1
It works perfectly now issue is I have multiple usernames in string, I tried using /g (global) but its not replacing properly:
Example string:
This is a string which has a #[User Full Name](contact:1) data inside. and it can also contain many other users data like #[Second Username](contact:2) and #[Third username](contact:3) and so many others....
when used global I get this result:
var re = /\#\[(.*)\]\(contact\:(\d+)\)/g;
text = text.replace(re,"username:$1 with ID: $2");
//RESULT from above
This is a string which has a user username; User Full Name](contact:1) data inside. and it can also contain many other users data like #[[Second Username](contact:2) and #[Third username and ID: 52 and so many others....
You just need a non greedy ? match in your first capture group. By having .* you are matching the most amount possible while if you use .*?, it matches the least amount possible.
/#\[(.*?)\]\(contact:(\d+)\)/
And if the word contact is not always there, you could do..
/#\[(.*?)\]\([^:]+:(\d+)\)/
See working demo
Can't say I can see how your resulting string is going to be usable. How about something like this...
var re = /#\[(.*?)\]\(contact:(\d+)\)/g;
var users = [];
var match = re.exec(text);
while (match !== null) {
users.push({
username: match[1],
id: match[2]
});
match = re.exec(text);
}
I have an input box where the a username is input'd but if invalid characters are input'd, I want it to error. The code below is what I'm using; What would i put in the "something" section?
var numbers = new RegExp("SOMETHING");
$(this).removeClass("active");
if(($(this).val() == "") || $(this).val().match(numbers))
{
$("#firstNameErrorMsg").html("First name can only contain letters. ");
}
else
{
$("#firstNameErrorMsg").html("OK");
}
Here are some patterns I wrote them long years ago:
patt['name'] = /^[a-z ,-]+$/i;
patt['username'] = /^[A-z0-9_-]+$/i;
patt['email'] = /^[a-z0-9]+(?:[\.-]?[a-z0-9]+)*#[a-z0-9]+([-]?[a-z0-9]+)*[\.-]?[a-z0-9]+([-]?[a-z0-9]+)*([\.-]?[a-z]{2,})*(\.[a-z]{2,5})+$/i;
patt['website'] = /^http(s)?:\/\/(www\.)?[a-z0-9]+([-]?[a-z0-9]+)*[\.-]?[a-z0-9]+([-]?[a-z0-9]+)*([\.-]?[a-z]{2,})*(\.[a-z]{2,5})+$/i;
patt['age'] = /^(?:([1][3-9]|[2-9][0-9]))$/i;
patt['subject'] = /[a-z0-9?!:;'&_\. ,-]+/i;
If you want to use them, you should check this condition:
if(($(this).val() == "") || ! $(this).val().match(patt['name'])){ // in case.
...
}
But if you want to check undesirable characters, it'll be a long pattern for username input.
Try this Regex
[A-Za-z]
This will match only lowercase and uppercase characters
Suggest you read a bit about regexes and experiment with them.
To get simply letters and nothing else, just do:
^[a-zA-Z]+$
That allows 1..n lowercase & uppercase letters to be found between start and end, nothing else. Sushanth's version will match partial pieces of the input, letting the user to use spaces, numbers, etc. elsewhere as long as there's one piece of of the input with a word in it.
This should be a full implementation of what you're trying to do:
var invalid = /[^A-Za-z]+/;
$(this).removeClass("active");
if($(this).val() == "" || invalid.test($(this).val()))
{
$("#firstNameErrorMsg").html("First name can only contain letters. ");
}
else
{
$("#firstNameErrorMsg").html("OK");
}
Sushanth is mostly correct, but you will need to match any number of letters, and it has to be from the start to the end only letters, so you should do something like this
var name = new RegExp('^[A-Za-z]+$');
$(this).removeClass('active');
if($(this).val().match(name)) {
$('#firstNameErrorMsg').html('OK');
} else {
$('#firstNameErrorMsg').html('First name can only contain letters.');
}
If you are looking for validating your users input , to only have letters , i would suggest using the char code, something like this :
add the keypress event on the input tag
for the event args passed, check the character code (Some browsers use keyCode, others use which)
function checkOnKeyDown(event){
if (event.KeyCode >= 65 && event.keyCode <=122)
{
//all ok here -- only upper/lowercase letters accepted
}
else
{
//wrong
}
}
Here is a list with all the keyCode to characters mapping ;) : http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes