Regex for contact number that does/doesn't start with a + - javascript

I have tried to create a basic South African contact number regex. Its not working though. The rules are simple.
10 digits or
11 digits if it starts with a +
Examples:
0119879874
0731231234
+27731231234
+27123456789
It must match only digits and length.
My attempt: [+\d]\d{9}\d{0,2}
I tested on the site https://regex101.com/ and it looked like it worked but not when i test it with /[+\d]\d{9}\d{0,2}/.test('12345gjhf6789123456')) then i get a true value.

You should specify ^ - begin of the string and end $
and
/^(\+\d)?\d{10}$/.test('12345gjhf6789123456'))

Rather than use a regex that will not provide any error messaging and is difficult to read (and maintain), I would suggest a simple validation function that lays out the rules explicitly:
function validate(num) {
if (num[0] === '+') {
return num.length === 11;
} else {
return num.length === 10;
}
}
This has a few advantages, including:
faster than a regex
easier to comment and expand later
can be replaced with a full blown predicate library or just an array of rules

Related

Phone validation

Near the end of my project and I require some assistant.I need a regex code to validate the phone number. If the phone number is not empty, validate that the phone number is in one of the following formats:
‘xxx–xxx-xxxx’ – 10 digits with two dashes where the first dash is between the third and fourth digits and the second dash is between the sixth and seventh digits.
‘xxxxxxxxxx’’ – all 10 digits, or,
‘(xxx)xxxxxxx’’ – 10 digits with the first three digits being enclosed by parentheses.
‘(xxx)–xxx-xxxx’ – 10 digits with the first three digits being enclosed by parentheses, and there is a dash between the sixth and seventh digits.
Also it needs to provide an alert if the phone number is not in the required format. All formats must be accepted by the validation or else it fails.
My issue is that I made an attempt to do this with regular expression because I feel that this is easy for me. I’m not an experience programmer at all so write codes have never been my thing and my question is there a RegExpression that covers all the formats at once and still able to give me an alert if no number is selected and the user not using one of the required formats.
Here is my current code but it does not cover the four formats.
var phone = document.myForm.phone.value;
if (!/^\d{3}-\d{3}-\d{4}$/.test(document.myForm.phone.value)) {
alert("Please enter the correct phone format ");
This code only covers xxx-xxx-xxxx. Is it possible to cover all formats with this kind of code? Please it must be regex starting with “var phone” like I have in my code example or it tends to get messy.
Thanks in advance
Regex can get pretty tricky if you're pretty new to it. Anytime I need to test some regex/find help I use Regexr. Pretty neat little sandbox for testing regex.
As for your question I think this will work nicely.
var phone = [
'555-555-5555',
'(555)-555-5555',
'(555)555-5555',
'5555555555',
'(555)5555555'
];
for ( var i = 0; i < phone.length; i++ ) {
if ( !/(?:\d{1}\s)?\(?(\d{3})\)?-?\s?(\d{3})-?\s?(\d{4})/.test(phone[i]) ) {
console.log(phone[i]+': invalid');
}
}
Also I did use one of the community regex snippets from the site I linked above. Not taking credit for that.
Your regex itself is almost there. If you want to make something 'optional' use ? before whatever you want to make optional. In this case ( ) should be optional so \(?\d{3}\)? would make the ( ) optional but still force \d{3} to be required.
Instead of making one complex/giant RegExp, why not test multiple simpler RegExp's?
var phones = [
'0123456789',
'012-345-6789',
'(012)3456789'
],
tests = [
/^\d{3}-\d{3}-\d{4}$/,
/^\d{10}$/
],
pre = document.getElementById('out');
phones.forEach(function (phone) {
pre.textContent += phone + ' : ';
var pass = tests.some(function (test) {
return test.test(phone.toString());
});
if (pass) {
pre.textContent += 'pass';
} else {
pre.textContent += 'fail'
}
pre.textContent += '\n';
});
<pre id="out"></pre>
I've only included 2 rules in this example, but you can see it will be much easier to maintain, add/remove rules.
(?:^\d{3}-\d{3}-\d{4}$)|(?:^\(\d{3}\)\d{3}-\d{4}$)|(?:[0-9]{10})
This will cover the three examples you mentioned.
(If you build each example by itself then concatenate with a pipe (equivalent to 'or') you can add more...)
However if you are going to do a catch for ALL Valid Phone Number Formats, this will get quite lengthy. At that point i would suggest a different approach.

Regex to replace a portion of a string

I've a chart which in the Y axis I have some numbers, like 40000000, 7000000, 20000000.
I'd like to use a Regex to replace the last six '0' numbers by 'M'
Example
40000000 should be 40M
7000000 should be 7M
20000000 should be 20M
If the number is less then 999999, should be replaced by the letter 'K'
4000 should be 4K
Can someone help me with this regex ?
Note someString has to be a string, not a number.
someString.replace(/0{6}$/, "M").replace(/0{3}$/, "K");
Untested from mobile, but try:
/0{6}$/
Full code:
'4000000'.replace(/0{6}$/,'M')
Addressing thousands:
'4000000'.replace(/0{6}$/,'M').replace(/0{3}$/,'K')
Working Sample for M
The regex used is /0{6}\b/g. Note that $ is not used to check the end of the string, but a word boundary character \b is used which makes this work in a wider range of cases in which other suggestions would fail.
You can very easily derive a similar one yourself for K, leaving that as an exercise for you :)
After you have done that, you can check if your data matches the first regex or not, and replace if it does. If it doesn't, then test for the second regex (for K) and replace if found.
P.S. The service I used to post the solution (Regex 101) is a very useful service and is a perfect tool for prototyping and learning regex.
http://jsh.zirak.me/2klw //see this only if you still can't figure out how to do it.
This spoiler contains the solution if you can't figure out how to do it
Another approach that produces exactly the desired output:
function getRepString (rep) {
rep = rep+''; // coerce to string
if (rep < 1000) {
return rep; // return the same number
}
if (rep < 10000) { // place a comma between
return rep.charAt(0) + ',' + rep.substring(1);
}
// divide and format
return (rep/1000).toFixed(rep % 1000 != 0)+'k';
}
I am not taking credit for this answer. This answer was by CMS at a duplicate question found here:
How to format numbers similar to Stack Overflow reputation format

Allowing a dash in this regex

I'm using this Wordpress plugin called 'Easy contact form' which offers standard validation methods.
It uses the following regex for phone numbers:
/^(\+{0,1}\d{1,2})*\s*(\(?\d{3}\)?\s*)*\d{3}(-{0,1}|\s{0,1})\d{2}(-{0,1}|\s{0,1})\d{2}$/
Just now it allows the following formats (maybe more):
0612345678
+31612345678
But I want it to allow +316-12345678 and 06-12345678 also ... Is this possible? If so, how?
Thanks in advance!
You can use a less complex regex :
^\+?\d{2}(-?\d){8,9}$
This regex allows a + at the beginning of the phone number, then matches two digits, and after that, digits preceded (or not) by a -, for a total of 10 or 11 digits.
Now you can adapt it if the initial + is only for 11-digits phone numbers :
^\+?\d{3}(-?\d){9}|\d{2}(-?\d){8}$
My regex allow you to use - every digit. If that's an issue, it can be changed :
^\+?\d{3}(-?\d{2}){4}|\d{2}(-?\d{2}){4}$
I think this last regex will answer your needs, and it's quite simple !
When you figure out what patterns you actually want to allow and not allow. Then fill them out in this function and if the statement returns true you have your regex.
var regex = /^\+?\d{3}(-?\d{2}){4}|\d{2}(-?\d{2}){4}$/; //this is your regex, based on #Theox third answer
//allowed patterns
['0612345678', '+31612345678', '+316-12345678', '06-12345678'].every(function(test) {
return regex.exec(test) !== null;
}) &&
//disallowed patterns, none right now
[].every(function(test) {
return regex.exec(test) === null;
});

Why is my Javascript RegEx quantifier "not working"?

This question seems to have such an easy answer and an ashaming one for me, that I hope you just comment, then I can delete the thread after solving. ;)
I have a problem with the {n} quantifier in my RegEx. It does not seem to work!
Here my code
document.time.Id.onkeyup = function() {
var that = this.value,
regex = /^[1-9]{1}/
if (that) {
if (!that.match(regex)) {
this.nextSibling.innerHTML="Number must be between '1' and '100'.";
} else {
this.nextSibling.innerHTML="";
}
} else {
this.nextSibling.innerHTML="";
}
}
As you can see, I want to match against 1 till 100 in the end, but I am stuck at the bit, that the quantifier does not work. When I key in 0 there is a match failure, as well with any letter...so it does work "a bit".
Can you please help me?
Your regular expression says to match any string that starts (because it's anchored at the beginning using ^) with any digit between 1 and 9. This is why it doesn't match 0 or letters.
A range validation is something you'd want to check using basic number comparisons:
var numberValue = parseInt(this.value, 10);
if (numberValue >= 1 && numberValue <= 100) {
// valid number
}
For the sake of completeness, you could create a regular expression for that purpose which I don't recommend, though:
^(?:[1-9][0-9]?|100)$
Try using this regex instead:
^[1-9][0-9]?$|^100$
The quantifier you used is actually redundant, since [1-9] and [1-9]{1} mean the same thing.
If you input 1000 with your current code and regex, the number will pass because a match counts as long as the regex matches any part of the string. Using $ (end of line anchor) forces the regex to check the whole string.
But you should probably be using a simple if check for that.
if (that > 0 && that <= 100 && that % 1 == 0) {
...
}

Test Password with Regex

I want to test a passwprd which must have at least 6 characters and 1 number in it. What regex string I can use with JS to get this done?
UPDATED
I forgot to write it must have at least 6 alpha characters and 1 numeric character but it should also allow special characters or any other character. Can you please modify your answers? I greatly appreciated your responses
This does smell a little like a homework question, but oh well. You can actually accomplish this concisely using a single regular expression and the "look ahead" feature.
/(?=.{6}).*\d.*/.test("helelo1")
The first bit in the brackets says "peek ahead to see if there's 6 characters". Following this we check for any number of characters, followed by a number, followed by any number of characters.
It is even possible to accomplish your goal in a single regex without having the faculty of look ahead... It's just a little hard to look at the solution and not wince:
new RegExp("[0-9].....|" +
".[0-9]....|" +
"..[0-9]...|" +
"...[0-9]..|" +
"....[0-9].|" +
".....[0-9]").test("password1")
Try this:
password.match(/(?=.*\d).{6}/);
More info here.
As far as I know this is best done with a combination of string functions and regex:
if( myPass.match(/[a-zA-Z]/).length >= 6 && myPass.match(/\d/g).length ) {
// Good passwords are good!
}
EDIT: Updated to include the new stipulations. Special characters are allowed, but not required.
if (/.{6,}/.test(password) && /\d/.test(password)) {
// success
} else {
// fail
}
/^(?=[\w\d]{6,}$)(?=.*\d)/.test(password)
requires 6 or more characters (letters, numbers or _)
requires at least one digit
won't allow any special characters
This is a js to check password,
it checks min 7 chars, contains 1 Upper case and 1 digit and 1 special character and must not contain a space, hope it will help you.
pwLength = this.value.length;
if (pwLength > 7 && pwLength < 21) {
charLengthIcon.removeClass("fail").addClass("pass");
}
else charLengthIcon.removeClass("pass").addClass("fail");
if (this.value.match(/[A-Z]/g)) {
capLetterIcon.removeClass("fail").addClass("pass");
}
else capLetterIcon.removeClass("pass").addClass("fail");
if (this.value.match(/[0-9]/g)) {
numberIcon.removeClass("fail").addClass("pass");
}
else numberIcon.removeClass("pass").addClass("fail");
if (this.value.match(/[##$%!$&~*^(){}?><.,;:"'-+=|]/g)) {
splcharIcon.removeClass("fail").addClass("pass");
}
else splcharIcon.removeClass("pass").addClass("fail");
if (this.value.match(/[\s/]/g)) {
whiteSpce.removeClass("pass").addClass("fail");
}
else whiteSpce.removeClass("fail").addClass("pass");
confirmPW();
});

Categories

Resources