Ensure user only enters string characters when prompted - javascript

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

Related

javascript .match function

I have the following javascript .match script to allow telephone numbers in form submit
var number = jQuery('#phone-number').val();
if ((number.match(/(\d)\1\1\1\1\1/))
|| (number.match(/(\d)(\d)\1\2\1\2\1\2/))
|| (number.match(/123456|234567|345678|456789|567890|987654|876543|765432|654321|543210/))
|| (!number.match(/^(0\d{8,10})?$/))) {
alert("Please supply a valid phone number");
return false;
}
Currently, it doesnt allow a SPACE between numbers.. I'm no good at regex and was wondering if someone could tell me how I allow a SPACE between any number using the script above?
thanks
Craig.
If you want to specify any number of spaces between each character, you can use \s*.
\s stands for whitespace character and * for any number of those
E.g.
\s*(\d)\s*\1\s*\1\s*\1\s*\1\s*\1\s*
const regex = /\s*(\d)\s*\1\s*\1\s*\1\s*\1\s*\1\s*/;
const tel1 = '111111';
const tel2 = ' 1 1 1 1 1 1';
console.log(regex.test(tel1));
console.log(regex.test(tel2));
Ugly, but:
if ((number.match(/(\d)\s*\1\s*\1\s*\1\s*\1\s*\1\s*/))
|| (number.match(/(\d)\s*(\d)\s*\1\s*\2\s*\1\s*\2\s*\1\s*\2\s*/))
|| (number.match(/123456|234567|345678|456789|567890|987654|876543|765432|654321|543210/))
|| (!number.match(/^(0(?:\s*\d\s*){8,10})?$/))) {
alert("Please supply a valid phone number");
return false;
}
For 1 space only replace \s* with \s?
You can remove all spaces from a string with
str = str.replace(/\s/g, '');
Then you can use your existing code.

Regex to allow only two words, one space and limit to 50 characters

I'm trying to build a regular expression with the following conditions:
Only two words
allow one space after the last word
Maximum length 50
like ("firstname lastname ")
Thanks.
Here is a regex which covers all your requirements, including the length check:
^(?!.{51,})(\w+\s+\w+ ?)$
Explanation:
^(?!.{51,}) assert that the string is not followed by 51 or more characters
(
\w+ match a word
\s+ followed by one or more spaces
\w+ followed by a second word
? ending with an optional space
)$
function tests(str){
var regex = /^(?!.{51,})(\w+\s+\w+ ?)$/;
if (regex.test(str)) {
console.log("passes");
}
else {
console.log("fails");
}
}
tests("firstname lastname "); // passes
tests("first name last name"); // fails
tests("123456789 1234567890123456789012345678901234567890"); // passes (length 50)
tests("123456789 12345678901234567890123456789012345678901"); // fails (length 51)
Regex 101
Try this:
const validate = data => /^\w+\s*\w+ ?$/.test(data) && data.length <= 50
const testData = ['this works', 'this too ', ' this fails', 'firstname lastname ', ' firstname middlename lastname ']
for (let temp of testData) {
console.log(`${temp} ${validate(temp)}`)
}
function tests(str){
var pat=/^[a-zA-Z]+\s[a-zA-Z]+\s?$/;
if(pat.test(str) && str.length<=50){
console.log("true");
}
else{
console.log("false");
}
}
tests("firstname lastname "); //true
tests("first name last name"); //flase
You can check word count by splitting string into array like this
var array = "some string".split(" "); //result - ["some","string"]
Now you can check word count
var count = array.length; //will return 2
You can count letters like this
var letterCount = "some string".length; //will return 11
Way easier and better than using regex.
This pattern will help /^[a-Z]+\s[a-Z]+\s?$/
<input type="text" pattern="^[a-Z]+\s[a-Z]+\s?$" title="Must be two words...">

Regular Expression to provided max 2 spaces

I have to write a regular expression in JavaScript which will satisfy the below
a) accept only alphabetic characters(small/caps)
b) should not exceed beyond 20 characters
c) max 2 spaces can be provided.
Valid test cases
a) Name
b) name
c) namea nameb
d) namea nameb namecd
e) namea nameb (2 consecutive spaces is also valid but total number of spaces cannot be more than 2)
My attempt (but not working)
function test(){
var originalString="abc rt t tt";
var myRegEx = /^([a-zA-Z ]{1,20})+$/;
var isValid = myRegEx.test(originalString);
alert(isValid);
}
What is the mistake and how to fix?
The regex /^([a-zA-Z ]{1,20})+$/ will match one to twenty alphabet and/or space one or more times. So, basically this allows alphabets and spaces in any sequence any number of times.
You can use
^[a-zA-Z]+(\s[a-zA-Z]*){0,2}$
Demo
var regex = /^[a-zA-Z]+(\s[a-zA-Z]*){0,2}$/;
var result = document.getElementById('result');
document.getElementById('text').addEventListener('keyup', function(e) {
var value = this.value;
var isValid = value.length <= 20 && regex.test(value);
result.innerHTML = isValid ? 'Valid' : 'InValid';
result.className = isValid ? 'valid' : 'invalid';
}, false);
input:valid, .valid {
color: green;
}
input:invalid, .invalid {
color: red;
}
<input id="text" pattern="[a-zA-Z]+(\s[a-zA-Z]*){0,2}" maxlength="20" />
<div id="result"></div>
Explanation:
[a-zA-Z]+ Match alphabets one or more times
\s: Matches a space character
{0,2}: Match previous class zero to two times.
To check if the string does not exceed 20 characters, String.length property can be used.
if (str.length <= 20 && regex.test(str)) {
// Valid
} else {
// Invalid
}
You can check that the input contains only letters, with a maximum of two internal spaces, as follows:
/^[a-z]+ ?[a-z]* ?[a-z]+$/i
In other words, starting at the beginning, match a sequence of one of more letters, then maybe a space, then a possibly empty bunch of letters, then maybe a space again, then finally a sequence of one or more letters taking you to the end.
To check the length, without having to check it using JS, add a look-ahead:
/^(?=.{1,20}$)[a-z]+ ?[a-z]* ?[a-z]+$/i
^^^^^^^^^^^^ LOOK-AHEAD TO LIMIT CHARS TO 20
This says, "look ahead and find between one and twenty characters up to the end of the string".

Javascript check for 1 special character and 2 digits

How to create a javascript validation for a password field which must contain at least one special character and at least two digits ?
Exact regular expression that perfect match to your query is below, it is tested ...
^(?=.*?[0-9].*?[0-9])(?=.*[!##$%])[0-9a-zA-Z!##$%]{8,}$
function check(str){
var temp = str;
if(/^[a-zA-Z0-9- ]*$/.test(str) == false && temp.replace(/[^0-9]/g,"").length>1) return true;
return false;
}

Checking for invalid characters from an input with jQuerys

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

Categories

Resources