mobile number validation using regex javascript - javascript

I want mobile number in format
+91(or any other country code)-9999999999(10 digit mobile number).
I have tried /^\+[0-9]{2,3}+[0-9]\d{10}, but its not working please help
Thanks in advance

Solution in short:
// should return an array with a single match representing the phone number in arr[0]
var arr = '+49-1234567890'.match(/^\+\d{1,3}-\d{9,10}$/);
// should return null
var nullVal = 'invalid entry'.match(/^\+\d{1,3}-\d{9,10}$/);
Longer explanation:
/ start regex
^ try to match from the beginning
\+ match a + sign
\d{1,3} match a digit 1 to 3 times
- match a dash
\d{9,10} match 9 or 10 digits
$ force the matching to be only valid if can be applied until string termination
/ finish regex
Knowing what the regex does, might let you modify it to your own needs
Sometimes it is good to ignore any whitespaces you come across. \s* matches 0 or n whitespaces. So in order to be more permissive you could let users input something like ' + 49 - 1232345 '
The regex to match this would be /^\s*\+\s*\d{1,3}\s*-\s*\d{9, 10}\s*$/ (just filled the possible space locations with \s*)
Other than that: I warmly recommend mastering regexes, because they come really handy in many situations.

If you are expecting a dash in the number (which your format shows), there is nothing in your regex to match it: is the second plus in the regex meant to be a dash?
^\+[0-9]{2,3}-[0-9]\d{10}
Also note that:
some country codes are single digit (eg. 1 for North America, 7 for Russia), these will not be matched
I doubt the local part of all mobiles everywhere is always 10 digits (eg. it won't be enough in countries with large populations as mobile ownership grows)

You can simply write the following:
var pattern=/^(0|[+91]{3})?[7-9][0-9]{9}$/;

\+[0-9]{2,3}-[0-9]+
Try this. This matches a + in the beginning, two or three numbers for the country code, followed by a - followed by any number of numbers

Use the mask function
jQuery(function($){
$("#phone").mask("999-999-9999",{placeholder:" "});
});
look here http://office.microsoft.com/en-in/access-help/control-data-entry-formats-with-input-masks-HA010096452.aspx

For mobile validation please try this
<html>
<head>
<title>Mobile number validation using regex</title>
<script type="text/javascript">
function validate() {
var mobile = document.getElementById("mobile").value;
var pattern = /^[7-9][0-9]{9}$/;
if (pattern.test(mobile)) {
alert("Your mobile number : "+mobile);
return true;
}
alert("It is not valid mobile number");
return false;
}
</script>
</head>
<body>
Enter Mobile No. :
<input type="text" name="mobile" id="mobile" />
<input type="submit" value="Check" onclick="validate();" />
</body>
</html>

Related

jQuery - regex for integer and comma(s) - should only accept hundreds, thousands and millions

Max value should be 99,999,999 (no period at the end). So it should accept:
123
1,234
10,000
100,000
1,000,000
99,000,000
etc.
I found this code that does if perfectly for floats:
HTML
<input type="text" class="numberOnly" name="example" value="" required>
jQuery:
$('.numberOnly').keyup(function() {
var valid = /^\-?\d+\.\d*$|^\-?[\d]*$/;
var number = /\-\d+\.\d*|\-[\d]*|[\d]+\.[\d]*|[\d]+/;
if (!valid.test($(this).val())) {
var n = this.value.match(number);
this.value = n ? n[0] : '';
}
});
The values it accepts are: 1.1, .1, 1 (And they can even be negative values.)
Whenever a user types an invalid value, for example 1.., it automatically deletes the invalid value which in this case is the second dot.
I wanted to do something similar for my question. Here's what I have so far but obviously it's not working.
HTML:
<input type="text" class="millions" name="example2" value="" required>
jQuery:
$('.millions').keyup(function() {
var valid = /^(\d[0-0]{0,3}[\,]\d{0,9}[\,])?\d{0,9}$/;
var number = /\d{0,9}[\,](\d{0,9}[\,]\d{0,9})?/;
if (!valid.test($(this).val())) {
var n = this.value.match(number);
this.value = n ? n[0] : '';
}
});
In addition to wanting to know the correct regex format that I need, can anyone also explain what are valid and number variables used for?
Thank you so much!
The valid pattern is the one you're interested in for server side checking. It's the pattern used to check that the whole string conforms to your requirements. The number pattern is the one used to do replacement when the user types an illegal character. The number pattern needs to be more relaxed to allow the user to enter subsequences of valid patterns (e.g. 1,0) which the user may then complete to a valid pattern.
This pattern will do what you require:
var valid = /^([1-9]\d?(,\d{3}){0,2}|[1-9]\d{0,2}(,\d{3})?|0)$/;
Breaking it down:
^( - start of line
[1-9]\d{0,2} - first group starts with a non-zero digit followed by 0-1 digits
(,\d{3}){0,2} - 0-2 or comma separated groups of three digits
|[1-9]\d{0,2}(,\d{3})? - or a three digit leading group followed by a three digit trailing group
|0 - "0" by itself is valid
)$ - end of line
The number pattern is more complicated as it has to allow a trailing comma and allow groups of less than three digits at the end.

Restrict accepting email that has non English characters

First of all, I checked possible solutions but couldn't find something that helps to solve my problem.
In short, I have existing logic that gets email from user and tests for few conditions, like make sure it doesn't have apostrophe, double # sign and consecutive dots and etc. The logic is not implemented using regex.
Now, I have new requirement, we need to restrict user from entering non English characters, by restrict I mean try to catch it while user is entering non english character or catch it while value is passed to javascript function that is verifying other conditions above.
So I found some answers here and tried them: here
Here is my code:
<input type="text" id="ctEmailAddress" name="ctEmailAddress" autocomplete="off"
size="40" maxlength="255" value="${userinfo.emailAddress}" oncopy="return false;" onpaste="return false;" onkeypress="suppressNonEng(event)">
And script:
function suppressNonEng(event){
var englishAlphabetAndWhiteSpace = /[A-Za-z ]/g;
var key = String.fromCharCode(event.which);
if (englishAlphabetAndWhiteSpace.test(key)) {
return true;
}
alert ("this is not in English");
return false;
}
So I used js function from link, it is separate from current logic. The problem is, it still allows to pass non english characters, for example french.
The same applies to this function:
function suppressNonEng(event){
var key = event.which;
if(key > 128){
alert("Email address can be entered only in English. Please try again.");
}
}
Again, French letters have no problem going through it.
My question is, how I can make sure that value is english characters only? Should I use regex for that or there is better solution? Please advice. Thanks.
Description
[^\x00-\x7F]+
This regular expression will match any character that is outside ascii 0-127
Example
Live Demo
https://regex101.com/r/qN7eP6/1
Sample text
Here are some sample non-english characters: ü, ö, ß, and ñ.
Sample Matches
[0][0] = ü
[1][0] = ö
[2][0] = ß
[3][0] = ñ
Explanation
NODE EXPLANATION
----------------------------------------------------------------------
[^\x00-\x7F]+ any character except: ascii 0-127 also known as
'\x00' to '\x7F' (1 or more times
(matching the most amount possible))
----------------------------------------------------------------------

Auto correct phone format input

I'm trying to auto format an input on HTML with javascript, and it is almost done, i need the format to be xxx-xxx-xxxx but and I have this code
this.value = this.value.replace(/(\d{3})\-?/g,'$1-');
as youy can see it will just auto format xxx-xxx-xxx but I need to be 4 digits at the end
any sugestions?
Try this regexp:
'1234567890'.replace(/(\d{3}(?!\d?$))\-?/g, '$1-'); // 123-456-7890
The part (?!\d?$) is a negative lookahead. It allows regular expression to match three digits only if they are not followed by another number (4th) (but not necessarily ?) at the end of the string $.
So it will not match 789 group because it's followed by 0$.
Or simply : .replace(/(\d{3})(\d{3})(\d{4})\-?/g,'$1-$2-$3');
Sample code to help you out:
var phone = '(555) 666-7777';
// First clean your input
phone = phone.replace(/[^\d]/g, '');
// Check the length of the phone
if(phone.length == 10){
// Now we can format the phone
phone = phone.substring(0,3)+'-'+phone.substring(3,6)+'-'+phone.substring(6, 10);
// Optionally
//phone = phone.replace(/(\d{3})(\d{3})/, '$1-$2-');
}
else {
// whatever you want to tell the user
}
there seems to be a bug in the "replace" regex's above. enter a 10 digit number and you see it formatted correctly (e.g. "(123) 456-7890"). Then, select the contents of the field (double or triple click it) and overtype the value. You'll see the first two digits get transposed. So if you enter 1 2 3, you'll see 2 1 3...

Regex to only allow numbers under 10 digits?

I'm trying to write a regex to verify that an input is a pure, positive whole number (up to 10 digits, but I'm applying that logic elsewhere).
Right now, this is the regex that I'm working with (which I got from here):
^(([1-9]*)|(([1-9]*).([0-9]*)))$
In this function:
if (/^(([1-9]*)|(([1-9]*).([0-9]*)))$/.test($('#targetMe').val())) {
alert('we cool')
} else {
alert('we not')
}
However, I can't seem to get it to work, and I'm not sure if it's the regex or the function. I need to disallow %, . and ' as well. I only want numeric characters. Can anyone point me in the right direction?
You can do this way:
/^[0-9]{1,10}$/
Code:
var tempVal = $('#targetMe').val();
if (/^[0-9]{1,10}$/.test(+tempVal)) // OR if (/^[0-9]{1,10}$/.test(+tempVal) && tempVal.length<=10)
alert('we cool');
else
alert('we not');
Refer LIVE DEMO
var value = $('#targetMe').val(),
re = /^[1-9][0-9]{0,8}$/;
if (re.test(value)) {
// ok
}
Would you need a regular expression?
var value = +$('#targetMe').val();
if (value && value<9999999999) { /*etc.*/ }
var reg = /^[0-9]{1,10}$/;
var checking = reg.test($('#number').val());
if(checking){
return number;
}else{
return false;
}
That's the problem with blindly copying code. The regex you copied is for numbers including floating point numbers with an arbitrary number of digits - and it is buggy, because it wouldn't allow the digit 0 before the decimal point.
You want the following regex:
^[1-9][0-9]{0,9}$
Use this regular expression to match ten digits only:
#"^\d{10}$"
To find a sequence of ten consecutive digits anywhere in a string, use:
#"\d{10}"
Note that this will also find the first 10 digits of an 11 digit number. To search anywhere in the string for exactly 10 consecutive digits.
#"(?<!\d)\d{10}(?!\d)"
check this site here you can learn JS Regular Expiration. How to create this?
https://www.regextester.com/99401

How can I implement a live Javascript Regex for phone numbers?

I have a text box and it says "Phone:" as the standard here for phone number is (XXX)-XXX-XXXX
I'd like to have a javascript that automatically puts my numbers into that format if it's not in that format, so if you typed 9993334444 then it would change it automatically on the fly as I'm typing to (999)-333-4444 I have looked around Google for Javascript Phone Regex to no success, maybe a Regex isn't what I'm looking for?
you want to add an onkeyup event with a regex like
this.value = this.value.replace(/^\(?([0-9][0-9][0-9]){1}\)?-?([0-9][0-9][0-9][0-9]){1}-?([0-9][0-9][0-9]){1}$/, '($1)-$2-$3');
Check out http://jsfiddle.net/R8enX/
/ means start/end a regex string
^ means start of matching string
$ means end of matching string
? means 0 or 1 instances (make braces and dashes optional)
[0-9] means any single digit
(x){1} tags x as an expression that we can reference in the replacement with a $ sign
EDIT: realized I missed a digit on the last group of numbers, the jsfiddle will only work (properly) with 3 digits in the last group
To build somewhat on #Andrews answer you can check for a valid (local)phone number via this method. If the number is shorter or larger than 10 digits, it collapses back into an invalid number
-
<input type="text" onBlur="localNumber(this.value)"/>
<div id="output"></div>
-
<script>
var localNumber = function(str){
repl = str.replace(/^([0-9]{3})([0-9]{3})([0-9]{4})$/, "($1)-$2-$3");
outp = document.getElementById('output');
if( repl.match(/\W/) )
{
outp.innerHTML = repl;
}
else
{
outp.innerHTML = 'Invalid number for this region';
}
}
</script>

Categories