Regex for Brazilian phone number - javascript

I am attempting to setup a regex verification for a user to enter a Brazilian telephone number. The formats I would need it to accept (or as close as possible) would be:
22-22222-2222 22222222222 (22) 22222 2222 (22)-22222-2222 22 22222 2222 (22)222222222
So it needs to accept numbers, spaces, dashes, parentheses only. Any advice on this would be greatly appreciated!

I just made a currently valid regex for Brazilian numbers:
^\s*(\d{2}|\d{0})[-. ]?(\d{5}|\d{4})[-. ]?(\d{4})[-. ]?\s*$
Check out the validation at https://regex101.com/r/safMl7/2
Will not get the country code, since we know it is from Brazil: +55.
Will work with the following examples, with or without spaces and dashes:
12 1234 1234
12 12345 1234
12345 1234
1234 1234
Each group of the regex will be divided by the correct brazilian grouping.
See this example: 62 98345 1234

If you always have the area code (DDD), try a simplified version of Frederiko's regular expression.
^(\d{2})\D*(\d{5}|\d{4})\D*(\d{4})$
Check out at https://regex101.com/r/M1DrBo.

What about this: \(?\d{2,}\)?[ -]?\d{4,}[\-\s]?\d{4}

Mask for brasil Phone using javascript
regex for format 11 digits: /(\d{2})(\d{1})(\d{4})(\d{4})/, "($1) $2 $3-$4
before no regex : 63991017575
After aply regex: (63) 9 9101-7575
EXAMPLE 1 USING THE JAVASCRIPT:
var number = '63992017738';
number = number.toString().replace(/(\d{2})(\d{1})(\d{4})(\d{4})/, "($1) $2 $3-$4")
Result: (63) 9 9201-7738
EXAMPLE 2 USING THE JAVASCRIPT:
var number = '63992017738';
number = number.toString().replace(/(\d{2})(\d{1})(\d{4})(\d{4})/, "$1 $2 $3-$4")
Result: 63 9 9101-7575
EXAMPLE 3 USING THE JAVASCRIPT:
now + country code
//if you need this: +55 (63) 9 9201-7131
var number = '5563992017131';
number = number.toString().replace(/(\d{2})(\d{2})(\d{1})(\d{4})(\d{4})/, "+$1 ($2) $3 $4-$5")
Result: +55 (63) 9 9201-7131

My answer came in the form of using the Jquery mask plugin. Was exactly what I needed and has much more functionality.
https://igorescobar.github.io/jQuery-Mask-Plugin/
$(document).ready(function () {
$('.input-telephone').mask('(99) 9999-9999?9');
});

The following use of Regex seems to catch around 20 of the most common ways to write a Brazilian phone number. Fix and mobile numbers included.
(\b\(\d{2}\)\s?[9]?\s?\d{4}(\-|\s)?\d\d{4})|(\b\d{2}\s?[9]?\s?\d{4}(\-|\s)?\d{4})|(\b([9]|[9]\s)?\d{4}(\-|\s)?\d{4})|(\b\d{4}(\-|\s)?\d{4})
There are four "or" options to match a number. It goes from the more complex one (with parenthesis and DDD code) to the most simple one (i. e. eight digit phone number).
I added the \b in front and not in the end of each case because sometimes you can catch cases where people write a number followed by some description: "99000-1100word". You can remove the word boundaries as you want, though:
(\(\d{2}\)\s?[9]?\s?\d{4}(\-|\s)?\d\d{4})|(\d{2}\s?[9]?\s?\d{4}(\-|\s)?\d{4})|(([9]|[9]\s)?\d{4}(\-|\s)?\d{4})|(\d{4}(\-|\s)?\d{4})

This is the simplier
regex for 10 digits format: (\d{2})(\d{4})(\d{4})
regex for 11 digits format: (\d{2})(\d{5})(\d{4})
Therefore, you could write a function to regex and replace:
export function phoneFormatter10(phone) {
phone = phone.replace(/[^\d]/g, ""); //remove all non digits
return phone.replace(/(\d{2})(\d{4})(\d{4})/, "($1)$2-$3");
}
export function phoneFormatter11(phone) {
phone = phone.replace(/[^\d]/g, ""); //remove all non digits
return phone.replace(/(\d{2})(\d{5})(\d{4})/, "($1)$2-$3");
}
Examples of use:
phoneFormatter10('3499883424')
result: '(34)9988-3424'
phoneFormatter11('3499^883*4-244') //even with badly formatted string
result: '(34)99883-4244'

Related

Regex that exclude specific pattern of ip

I am filtering specific ip address via regex. For example,
all the ip address containing 1 in the last octet i.e. XXX.XXX.XXX.1 should be excluded but not 11 or 123 or 125. Sample example:
the regex should discard
192.168.1.1
192.168.20.1
192.168.30.1
but should not discard
192.168.1.101
192.168.20.103
I have tried the regex as :
^(?!\d{1,3}\.\d{1,3}\.\d{1,3}\.[^\1]).*$
but could not exclude as expected.
Any help is appreciated !!!
When matching the final octet, use (?:1\d+|[02-9]\d*)$ - either match a 1 which is followed by other digits, or match something which isn't a 1, possibly followed by other digits:
^\d{1,3}(?:\.\d{1,3}){2}\.(?:1\d+|[02-9]\d{0,2})$
https://regex101.com/r/gB5c6z/1
Another option, with negative lookahead:
^\d{1,3}(?:\.\d{1,3}){2}\.(?!1$)\d{1,3}$
considering given format and ip's will be valid you can use endsWith
let ips = [`192.168.1.1`, `192.168.20.1`, `192.168.30.1`, `192.168.1.101`, `192.168.20.103`]
let checker = (str) => !str.endsWith(`.1`)
ips.forEach(v => console.log(checker(v)))

Regex to match if string contains integer/decimal with digits

I want to write a regex that allows an integer number, or a decimal number with 0 - 2 decimal digits.
Valid Input
1
1.
1.1
1.11
111111111
111111111.
111111111.1
111111111.11
Invalid Input
a
a.
1.a
1.111
1.1111
string allows any number of digit characters, but only allows 1 decimal/period
if a period/decimal exists: only allow 2 digit characters after the decimal
Here is the regex I came up with
\d*\.?([\d]){0,2}
I am having trouble testing it to ensure it works. I found a couple ways of testing it. Using the test method which I just used w3schools setup here. The other way was with some javascript regular expression tester like regexr and regex101. For all of these: it appears that either my regular expression is returning false positives, or my regular expression does not work as intended.
Question: What regex would do what I want it to do?
You need to make sure that you check the complete string (from the first char to the last char) using ^...$
The first digit should appear at least 1 time (so you want to use + and not *).
Check this example:
r = /^\d+\.?\d{0,2}$/
tests = ['1', '1.', '1.1', '1.11', '111111111', '111111111.', '111111111.1', '111111111.11', 'a', 'a.', '1.a', '1.111', '1.1111']
tests.forEach(function(val) {
console.log(val, val.match(r) ? ': valid' : ': invalid');
});
update
Following the comments - if you need a solution for "integer number, or a decimal number with 0 - 2 decimal digits" (like you said in the question, but not like the valid input section), you can use this:
r = /^\d+(\.\d\d{0,1})?$/
console.log('1.'.match(r))
tests = ['1', '1.', '1.1', '1.11', '111111111', '111111111.', '111111111.1', '111111111.11', 'a', 'a.', '1.a', '1.111', '1.1111']
tests.forEach(function(val) {
console.log(val, val.match(r) ? ': valid' : ': invalid');
});
Don't forget closing and opening in Regex, many new Regex for get it and they end up unwanted result, everything should between ^ and $, ^ is starting point of the word(digit) boundary and $ is ending point...something like below should help you, try:
'use strict';
var decimal = /^\d+(\.\d\d{0,2})$/, num = 111111111.11;
console.log(decimal.test(num));
Hope this helps...

Number extraction from string using regex working partially

I'm extracting the phone numbers that begin with 9 followed by other 9 digits from tweets using JavaScript.
Here's the regex pattern I am using:
var numberPattern = /^9[0-9]{9}/;
Here's the pattern matching phase:
var numberstring = JSON.stringify(data[i].text);
if(numberPattern.test(data[i].text.toString()) == true){
var obj={
tweet : {
status : data[i].text
},
phone : numberstring.match(numberPattern)
}
//console.log(numberstring.match(numberPattern));
stringarray.push(obj);
The problem is it is working for few numbers and not all. Also, I want to modify the regex to accept +91 prefix to numbers as well and(or) reject a starting 0 in numbers. I'm a beginner in regex, so help is needed. Thanks.
Example:
#Chennai O-ve blood for #arun_scribbles 's friend's father surgery in few days. Pl call 9445866298. 15May. via #arun_scribbles
Your regex pattern seems to be designed to allow a 9 or 8 at the beginning, but it would be better to enclose that choice in parentheses: /^(9|8)[0-9]{9}/.
To allow an optional "+" at the beginning, follow it with a question mark to make it optional: /^\+?(9|8)[0-9]{9}/.
To allow any character except "0", replace the (9|8) with a construct to accept only 1-9: /^\+?[1-9][0-9]{9}/.
And in your example, the phone number doesn't come at the beginning of the line, so the caret will not find it. If you're looking for content in the middle of the line, you'll need to drop the caret: /\+?[1-9][0-9]{9}/.
var numberPattern = /([+]91)?9[0-9]{9}\b/;
Try this regex pattern: [\+]?[0-9]{1,4}[\s]?[0-9]{10}
It accepts any country code with +, a space, and then 10 digit number.

JavaScript Validate Phone Number Using Regex

Greetings overflowers,
I'm trying to write a regular expression to validate phone numbers of the form ########## (10 digits)
i.e. this is these are cases that would be valid: 1231231234 or 1111111111. Invalid cases would be strings of digits that are less than 10 digits or more than 10 digits.
The expression that I have so far is this:
"\d{10}"
Unfortunately, it does not properly validate if the string is 11+ digits long.
Does anyone know of an expression to achieve this task?
You need to use ancors, i.e.
/^\d{10}$/
You need to anchor the start and the end too
/^\d{10}$/
This matches 10 digits and nothing else.
This expression work for google form 10 digit phone number like below:
(123) 123 1234 or 123-123-1234 or 123123124
(\W|^)[(]{0,1}\d{3}[)]{0,1}[\s-]{0,1}\d{3}[\s-]{0,1}\d{4}(\W|$)
I included the option to use dashes (xxx-xxx-xxxx) for a better user experience (assuming this is your site):
var regex = /^\d{3}-?\d{3}-?\d{4}$/g
window.alert(regex.test('1234567890'));
http://jsfiddle.net/bh4ux/279/
I usually use
phone_number.match(/^[\(\)\s\-\+\d]{10,17}$/)
To be able to accept phone numbers in formats 12345678, 1234-5678, +12 345-678-93 or (61) 8383-3939 there's no real convention for people entering phone numbers around the world. Hence if you don't have to validate phone numbers per country, this should mostly work. The limit of 17 is there to stop people from entering two many useless hyphens and characters.
In addition to that, you could remove all white-space, hyphens and plus and count the characters to make sure it's 10 or more.
var pureNumber = phone_number.replace(/\D/g, "");
A complete solution is a combination of the two
var pureNumber = phone_number.replace(/\D/g, "");
var isValid = pureNumber.length >= 10 && phone_number.match(/^[\(\)\s\-\+\d]{10,17}$/) ;
Or this (which will remove non-digit characters from the string)
var phoneNumber = "(07) 1234-5678";
phoneNumber = phoneNumber.replace(/\D/g,'');
if (phoneNumber.length == 10) {
alert(phoneNumber + ' contains 10 digits');
}
else {
alert(phoneNumber + ' does not contain 10 digits');
}

allow input with decimal places upto 3

I want to allow only integers and floats (upto 3 decimal places) in a text box, how can I achieve this using javascript?
Valid values are
1234
12.3
12.314
1.11
0.4
Not valid
1.23456
abcd or any other character
Based on the comment that you need to also match ".1" you need to add a conditional with the first part of the regular expression.
var re = /^(\d+)?(?:\.\d{1,3})?$/;
Rough test suite - jSFiddle
You can use a regular expression to do this:
/^\d+(?:\.\d{1,3})?$/
That's the start of the string (^), one or more digits (\d+), optionally followed by a . and between 1 and 3 digits ((?:\.\d{1,3})), then the end of the string ($).
To compare it to the value of an input, you'd do something like this:
var re = /^\d+(?:\.\d{1,3})?$/;
var testValue = document.getElementById('id-of-input').value;
if(re.test(testValue)) {
// matches - input is valid
}
else {
// doesn't match - input is invalid
}
Take a look at this jsFiddle demo.
use regular expression to validate your input field , regular rexpression is as below
^[0-9]+(?:\.[0-9]{1,3})?$
Try this:
var reg=/^[\d]+(?:\.\d{1,3})?$/;
str=10.2305;
str1=123;
alert(reg.test(str));
alert(reg.test(str1));
Check Fiddle http://jsfiddle.net/8mURL/1

Categories

Resources