javascript .match function - javascript

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.

Related

Ensure user only enters string characters when prompted

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

Match special characters regex in Javascript (Random place)

I'm trying to make a regex to match atleast two special characters,
for a password strength checker. I now have this in Javascript:
if (password.match(/([^A-Za-z0-9]{2,})/)) {
//Add strength
}
But this checks that atleast two special characters that needs to be after each other. How can I make it, so that it will also check if it's not after each other?
Example:
_aaa!* //Match
a!a_a* //Also match
One way to do it:
var password = 'a!a_a*';
var matches = password.match(/([^A-Za-z0-9])/g);
if (matches && matches.length >= 2) {
console.log('Good');
} else {
console.log('Bad');
}
console.log(matches);
You could use replace for this:
var password = 'a!a_a*';
var specialChars = password.replace(/[A-Za-z0-9]/g, '');
console.log(password, specialChars.length > 1 ? 'OK' : 'Too few special chars');
^(.*?[\*\& list all the special characters you want to allow here prefixed by \]){2,}.*$
You can test it here: https://regex101.com/

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;
}

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