Regular Expression to provided max 2 spaces - javascript

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

Related

RegEx which tests if sentence contain every letter from polish alphabet

function isPangram(sentence) {
const polishSpecial = /[śćóźąęłżń]/;
const RegEx = /(\w).*\1/;
return !RegEx.test(sentence);
}
Mine regular expression only checks whether the letter is repeating itself. I want also add these polish special characters to the main RegEx.
The point is that sentence can only have one letter from [a-z] and [śćóźąęłżń], then it's true. If sentence doesn't have even one letter from [a-z] or [śćóźąęłżń], then it's false.
You can use
const ContainsAllPolishLetters = (str) =>
{
return [...new Set(str.match(/[A-Za-zżźćńółęąśŻŹĆĄŚĘŁÓŃ]/g))].length == 64;
}
console.log(ContainsAllPolishLetters("...AaĄąBbCcĆćDdEeĘęFfGgHhIiJjKkLlŁłMmNnŃńOoÓóPpRrSsŚśTtUuWwYyZzŹźŻż..."));
console.log(ContainsAllPolishLetters("...A tu mamy za mało polskich liter..."));
Details:
.match(/[A-Za-zżźćńółęąśŻŹĆĄŚĘŁÓŃ]/g - extracts all Polish letters from a str string
[...new Set(<result_of_Step_1>)] - removes duplicate letters from the array
<result_of_the_above>.length == 64 - checks if the count of unique letters is equal to 64, 32 lower- and 32 uppercase Polish letter count. If yes, the return value is true, otherwise, false.

Regex for min 8 characters, one uppercase letter and min one number not on the beginning and the end of the string

This is the description:
must be at least 8 characters long
string must contain at least one uppercase letter
the number must divide the string into at least two character strings
Examples:
Bad strings: asdFghjk, 123aSdfghjk, asd6H
Matching string: asd3fGhjk
So far I got this:
^(?!(0-9))(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{8,}$(?!(0-9))
You can check the length of string manually and then
^(?=.*[A-Z])(?:[a-zA-Z]+?\d+[a-zA-Z]+?)+$
let arr = ['asdFghjk','123aSdfghjk','asd6H','asd3fGhjk','aAs2323ASDdncnc','a1a1a1a1a1A','dgd3323hdhdh132asas']
let tester = (str) =>{
return str.length > 7 && /^(?=.*[A-Z])(?:[a-zA-Z]+?\d+[a-zA-Z]+?)+$/.test(str)
}
arr.forEach(str=>{
console.log(str, ' --> ',tester(str))
})

only accepting letters and spaces, numbers and spaces, and letters and numbers with spaces in different boxes

I can't figure out why these regular expressions aren't working correctly.
I need 3 different types of expression checks, but the methods aren't working fully like they are suppose to. They work "partially" as shown in example for #output2 where the response turns out to be an invalid, but it doesn't catch the first one. I'm assuming there's something small i'm missing?
I'm trying to do the following validations...
EDIT FOR CLARIFICATION SORRY!
var letters - should only accept letters with absolutely no digits or special characters, but still allow for spaces but only a max of 1 space (so no double spaces) and can't lead or end with a space. An empty string should still pass as being valid.
var digits - same as var letters, but digits only with no letters with no special characters. No leading or training spaces or double spaces anywhere. Blank entry is still valid.
var lettersDigits - only allow letters and digits with no special characters. No leading or training spaces or double spaces anywhere. Blank entry is still valid.
https://jsfiddle.net/umdhh5fb/
var value = '2 a s 2 s 2 a';
var valueInValid = 'a a a a a 2'
var valueDigits = '12321 asda 12312 2';
var letters = /([a-zA-Z]+\s)*[a-zA-Z]+$/; // only letters with no more than 2 spaces
var digits = /[\d+\s]*[\d]+$/; // only digits with no more than 2 spaces
var lettersDigits = /[a-zA-Z\d+\s]*[a-zA-Z\d]+$/; // digits and letters allowed no special characters no more than 2 spaces
if (letters.test(value) == false) {
$("#output").text("invalid");
} else {
$("#output").text("valid");
}
if (letters.test(valueInValid) == false) {
$("#output2").text("invalid");
} else {
$("#output2").text("valid");
}
if (digits.test(valueDigits) == false) {
$("#output3").text("invalid");
} else {
$("#output3").text("valid");
}
if (lettersDigits.test(value) == false) {
$("#output4").text("invalid");
} else {
$("#output4").text("valid");
}
<div id="output"></div> /* returns valid */
<div id="output2"></div> /* returns invalid */
<div id="output3"></div> /* returns valid */
<div id="output4"></div> /* returns valid */
You need to add the anchor ^ to the beginning of your regular expressions, so that it matches the whole value, not just the end of the value.
To make something optional, follow it with ?. To allow at most one space between things, make an expression that ends with space optional. And to allow an empty input, make everything between ^ and $ optional.
var value = '2 a s 2 s 2 a';
var valueInValid = 'a a a a a 2'
var valueDigits = '12321 asda 12312 2';
var letters = /^(([a-z]+\s)?[a-z]+)?$/i; // only letters with no more than 1 spaces
var digits = /^((\d+\s)?\d+)?$/; // only digits with no more than 1 spaces
var lettersDigits = /^(([a-z\d]+\s)?[a-z\d]+)?$/i; // digits and letters allowed no special characters no more than 1 spaces
if (letters.test(value) == false) {
$("#output").text("invalid");
} else {
$("#output").text("valid");
}
if (letters.test(valueInValid) == false) {
$("#output2").text("invalid");
} else {
$("#output2").text("valid");
}
if (digits.test(valueDigits) == false) {
$("#output3").text("invalid");
} else {
$("#output3").text("valid");
}
if (lettersDigits.test(value) == false) {
$("#output4").text("invalid");
} else {
$("#output4").text("valid");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="output"></div>
<div id="output2"></div>
<div id="output3"></div>
<div id="output4"></div>

javascript regular expression test for 6 digit numbers only. comma seperated

and so this must pass:
454555, 939999 , 019999 ,727663
its for a user entering 6 digit invoice numbers. it should fail if a number is 5 or 7 digit and not 6. so 1234567, 123456 should fail, as one set is more than 6 numbers.
So far I have :
[0-9]{6}(\s*,*,\s*[0-9]{6})*
which only draw back is that it accepts 7 or more digit numbers. cant figure out if its even possible at this point to do both, test for 6 digits separated by a comma and one or more space, and all the digits have to be only 6 digits and fail if one is not.
any help appreciated. regular expressions are not my forte.
thanks
Norman
You can write it using regex like the function below.
const isPassword = (password: string) => /^\d{6}$/gm.test(password);
And here is an example test file below.
test('should recognize a valid password', () => {
expect(isPassword('123456')).toBe(true);
expect(isPassword('000000')).toBe(true);
});
test('should recognize an invalid password', () => {
expect(isPassword('asdasda1234')).toBe(false);
expect(isPassword('1234567')).toBe(false);
expect(isPassword('a123456a')).toBe(false);
expect(isPassword('11.11.11')).toBe(false);
expect(isPassword('aaaaaa')).toBe(false);
expect(isPassword('eeeeee')).toBe(false);
expect(isPassword('......')).toBe(false);
expect(isPassword('werwerwerwr')).toBe(false);
});
In order to validate the full string you can use this regex.
^(\s*\d{6}\s*)(,\s*\d{6}\s*)*,?\s*$
It works with six digits only, and you have to enter at least one 6 digit number.
It also works if you have a trailing comma with whitespaces.
It's accepting more than six digit numbers because you're not anchoring the text, and for some odd reason you're optionally repeating the comma. Try something like this:
^[0-9]{6}(?:\s*,\s*[0-9]{6})*$
Also note that [0-9] is equivalent to \d, so this can be rewritten more concisely as:
^\d{6}(?:\s*,\s*\d{6})*$
Your regex does not match 7 digits in a row, but it also doesn't enforce that it matches the whole string. It just has to match some substring in the string, so it would also match each of these:
"1234512345612345612345"
"NaNaNaN 123456, 123456 BOOO!"
"!##$%^&*({123456})*&^%$##!"
Just add the start of string (^) and end of string ($) anchors to enforce that the whole string matches and it will work correctly:
^[0-9]{6}(\s*,*,\s*[0-9]{6})*$
Also note that ,*, could be shortened to ,+, and if you only want one comma in a row, just use ,, not ,* or ,+.
You can also replace [0-9] with \d:
^\d{6}(\s*,\s*\d{6})*$
Using only regex:
var commaSeparatedSixDigits = /^(?:\d{6}\s*,\s*)*\d{6}$/;
if (myInput.test(commaSeparatedSixDigits)) console.log( "Is good!" );
This says:
^ - Starting at the beginning of the string
(?:…)* - Find zero or more of the following:
\d{6} - six digits
\s* - maybe some whitespace
, - a literal comma
\s* - maybe some whitespace
\d{6} - Followed by six digits
$ - Followed by the end of the string
Alternatively:
var commaSeparatedSixDigits = /^\s*\d{6}(?:\s*,\s*\d{6})*\s*$/;
I leave it as an exercise to you to decipher what's different about this.
Using JavaScript + regex:
function isOnlyCommaSeparatedSixDigitNumbers( str ){
var parts = srt.split(/\s*,\s*/);
for (var i=parts.length;i--;){
// Ensure that each part is exactly six digit characters
if (! /^\d{6}$/.test(parts[i])) return false;
}
return true;
}
I see a lot of complication here. Sounds to me like what you want is pretty simple:
/^(\d{6},)*\d{6}$/
Then we account for whitespace:
/^\s*(\d{6}\s*,\s*)*\d{6}\s*$/
But as others have noted, this is actually quite simple in JavaScript without using regex:
function check(input) {
var parts = input.split(',');
for (var i = 0, n = parts.length; i < n; i++) {
if (isNaN(+parts[i].trim())) {
return false;
}
}
return true;
}
Tested in the Chrome JavaScript console.
There isn;t any real need for a regexp. Limit the input to only 6 characters, only accept numbers and ensure that the input has 6 digits (not show here). So you would need:
HTML
<input type='text' name='invoice' size='10' maxlength='6' value='' onkeypress='evNumersOnly(event);'>
JavaScript
<script>
function evNumbersOnly( evt ) {
//--- only accepts numbers
//--- this handles incompatabilities between browsers
var theEvent = evt || window.event;
//--- this handles incompatabilities between browsers
var key = theEvent.keyCode || theEvent.which;
//--- convert key number to a letter
key = String.fromCharCode( key );
var regex = /[0-9]/; // Allowable characters 0-9.+-,
if( !regex.test(key) ) {
theEvent.returnValue = false;
//--- this prevents the character from being displayed
if(theEvent.preventDefault) theEvent.preventDefault();
}
}
</script>

How do I use a regular expression to match a fixed-length number with a hyphen in the middle?

I am new to regular expressions and wanted to know how to write a regular expression that does the following:
Validates a string like 123-0123456789. Only numeric values and a hyphen should be allowed. Also, verify that there are 3 numeric chars before the hyphen and 10 chars after the hyphen.
The given answers won't work for strings with more digits (like '012-0123456789876'), so you need:
str.match(/^\d{3}-\d{10}$/) != null;
or
/^\d{3}-\d{10}$/.test(str);
Try this:
^\d{3}-\d{10}$
This says:
Accept only 3 digits, then a hyphen, then only 10 digits
Sure, this should work:
var valid = (str.match(/^\d{3}-\d{10}$/) != null);
Example:
> s = "102-1919103933";
"102-1919103933"
> var valid = s.match(/\d{3}-\d{10}/) != null;
> valid
true
> s = "28566945";
"28566945"
> var valid = s.match(/\d{3}-\d{10}/) != null;
> valid
false

Categories

Resources