How to modify regex for phone numbers and accept only digits - javascript

I have this following regex method for the jquery validate plugin.
jQuery.validator.addMethod("phoneUS", function(phone_number, element) {
phone_number = phone_number.replace(/\s+/g, "");
return this.optional(element) || phone_number.length > 9 &&
phone_number.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/);
}, "Please specify a valid phone number");
Currently, its validating against phone numbers in this format : 203-123-1234
I need to change to validate like this: 2031231234
Does anyone have a quick and easy solution for me?

You can replace
phone_number.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/);
with this
phone_number.match(/\d{10}/);
\d means match any digit
and
{10} means 10 times

Getting rid of all those -? sequences is probably the quickest way - they mean zero or one - characters.
That will reduce it to:
/^(1)?(\([2-9]\d{2}\)|[2-9]\d{2})[2-9]\d{2}\d{4}$/
whih can be further simplified to:
/^1?(\([2-9]\d{2}\)|[2-9]\d{2})[2-9]\d{6}$/
If you also want to disallow the brackets around area codes, you can further simplify it to:
/^1?[2-9]\d{2}[2-9]\d{6}$/
(and, technically, it won't match the literal 203-123-1234 since the character immediately after that first - has to be 2 thru 9, so I'm assuming you were just talking about the format rather than the values there).

I think better approach would be changing the whole expression with simpler version, something like this:
/^[0-9]{10}$/
Edited, Note (see comments):
This is just a limited example of how to validate a format: 111-222-3333 vs 1112223333, not proper US phone number validation.

If you just want ten digits, then
phone_number.match(/\d{10}/)
will do it. If you want to match any of the other conditions in there (eg match both 1-2031231234 and 2031231234), you will need to add more.
As a side note, what you currently have doesn't match 203-123-1234 because the first digit after the first hyphen is a 1, and it is looking for 2-9 in that spot.

([0-9]{10}) this will match with 10 digit number.

You can use if you want to match all formats, including 203-123-1234 and 2031231234
EDIT : I'm no regex expert, but I added "1-" support
/^(?:1-?)?[(]?\d{3}[)]?\s?-?\s?\d{3}\s?-?\s?\d{4}$/
By the way, there's a really nice AIR tool for regex, it's called RegExr and you can get the desktop version here http://www.gskinner.com/RegExr/desktop/ or use the online version http://gskinner.com/RegExr/ . There's also a "community" section that contains a lot of useful working regex. That's where I took that one.

Related

AngularJS: create a regex for first two character of a string alphabet and rest should be numeric

Never really used AngularJS and am having issues figuring out how to create a regex for an input to check/allow only first 2 characters to be letters & the rest numbers.
Hope this makes sense.
Using pugJS
.e-field
label.e-field__label(for='invoiceNr') Invoice Number
input#invoiceNumberInput.e-input(
ng-model='$ctrl.invoiceNumber'
name="invoiceNumber"
ng-required="true"
invoiceNr example: HN123123123
The ng-pattern was the answer. This is what I used:
ng-pattern="/^[a-zA-Z]{2}[0-9]{6,}$/"
Regex for first 2 character is number and rest is digits in angularJS input is as below. Use ng-pattern and the specified RegEX
ng-pattern="/^[a-zA-Z]{2}[0-9]*$/"
Not sure about the integration into Angular. However as a RegEx I think you could use this:
^[a-zA-Z]{2}[0-9]+$
(See test here)
...Just a quick comment regarding the use of ..[0-9]+$ as opposed to ...[0-9]*$
I think you should use + and not *. Otherwise a string like "HN" will also validate but I understood you only want to validate if it has numbers after the letters (like "HN1" or "HN123"..). For this case you should use "+".

Is it possible to have an emoji-only text input?

I'm building an Ionic2 app and one of my text fields needs to be an emoji-only field.. to make my situation a little harder, the input field can only be 1 emoji long.
From what I know of emojis, some are considered 2 characters, and some are 1, which makes me wonder how I can force only 1 emoji length in a text input.
Is this possible? Essentially just a text field that only accepts 1 emoji..
Any feedback would be great. Thank you!
Since you haven't yet provided your own code I'm not going to answer your whole question.
You could start off by using a regular expression that only allows characters and then modify it using something like the emoji regex library provided below.
var val = "šŸ¬";
if (val.match(/[^a-zA-Z]/g)) { // NOTE: will also match only characters
console.log(val);
} else {
console.log("Only characters allowed.")
}
You could also try a library like the following that's a regular expression to match all Emoji-only symbols as per the Unicode Standard. https://mths.be/emoji-regex
There's also a great article on Optimizing RegEx for Emoji.

Phone number validation - excluding non repeating separators

I have the following regex for phone number validation
function validatePhonenumber(phoneNum) {
var regex = /^[1-9]{3}[-\s\.]{0,1}[0-9]{3}[-\s\.]{0,1}[0-9]{4}$/;
return regex.test(phoneNum);
}
However, I would liek to make sure it doesn;t pass for different separators such as in
111-222.3333
Any ideas how to make sure the separators are the same always?
Just make sure beforehand that there is at most one kind of separator, then pass the string through the regex as you were doing.
function validatePhonenumber(phoneNum) {
var separators = extractSeparators(phoneNum);
if(separators.length > 1) return false;
var regex = /^[1-9]{3}[-\s\.]{0,1}[0-9]{3}[-\s\.]{0,1}[0-9]{3}$/;
return regex.test(phoneNum);
}
function extractSeparators(str){
// Return an array with all the distinct chars
// that are present in the passed string
// and are not numeric (0-9)
}
You can use the following regex instead:
\d{3}([-\s\.])?\d{3}\1?\d{4}
Here is a working example:
http://regex101.com/r/nN9nT7/1
As result it will match the following result:
111-222-3333 --> ok
111.222.3333 --> ok
111 222 3333 --> ok
111-222.3333
111.222-3333
111-222 3333
111 222-3333
EDIT: after Alan Moore's suggestion:
Also matches 111-2223333. That's because you made the \1 optional,
which isn't necessary. One of JavaScript's stranger quirks is that a
backreference to a group that did not participate in the match,
succeeds anyway. So if there's no first separator, ([-\s.])? succeeds
because the ? made it optional, and \1 succeeds because it's
JavaScript. But I would have used ([-\s.]?) to capture the first
separator (which might be nothing), and \1 to match the same thing
again. This works in any flavor, including JavaScript.
We can improve the regex to:
^\d{3}([-\s\.]?)\d{3}\1\d{4}$
You'll need at least two passes to keep this maintainable and extensible.
JS' RegEx doesn't allow for creating variables for use later in the RegEx, if you want to support older browsers.
If you are only supporting modern browsers, Fede's answer is just fine...
As such, with ghetto-support, you aren't going to be able to reliably check that one separator is the same value every time, without writing a really, really, really, stupidly-long RegEx, using | to basically write out the RegEx 3 times.
A better way might be to grab all of the separators, and use a reduction or a filter to check that they all have the same value.
var userEnteredNumber = "999.231 3055";
var validNumber = numRegEx.test(userEnteredNumber);
var separators = userEnteredNumber.replace(/\d+/g, "").split("");
var firstSeparator = separators[0];
var uniformSeparators = separators.every(function (separator) { return separator === firstSeparator; });
if (!uniformSeparators) { /* also not valid */ }
You could make that a little neater, using closures and some applied functions, but that's the idea.
Alternatively, here's the big, ugly RegEx that would allow you to test exactly what the user entered.
var separatorTest = /^([0-9]{3}\.[0-9]{3}\.[0-9]{3,4})|([0-9]{3}-[0-9]{3}-[0-9]{3,4})|([0-9]{3} [0-9]{3} [0-9]{3,4})|([0-9]{9,10})$/;
Notice I had to include the exact same number-test three times, wrap each one in parens (to be treated as a single group), and then separate each group with an | to check each group, like an if, else if, else... ...and then plug in a separate special case for having no separator at all...
...not pretty.
I'm also not using \d, just because it's easy to forget that - and . are both accepted "digit"s, when trying to maintain one of these abominations.
Now, a word or two of warning:
People are liable to enter all kinds of crap; if this is for a commercial site, it's likely better to just strip separators entirely and validate the number is the right size, and conforms to some specifics (eg: doesn't start with /^555555/).
If not given any instruction about number format, people will happily use either no separator or a formal number, like (555) 555-5555 (or +1 (555) 555-5555 for the really pedantic), which is obviously going to fail hard, in this system (see point #1).
Be prepared to trim what you get, before validating.
Depending on your country/region/etc laws about data-security and consumer-vs-transaction record-keeping (again, may or may not be more important in a commercial setting), it's likely better to store both a "user-given" ugly number, and a system-usable number, which you either clean on the back-end, or submit along with the user-entered text.
From a user-interaction perspective, either forcing the number to conform, explicitly (placeholders showing them xxx-xxx-xxxx right above the input, in bold), or accepting any text, and prepping it yourself, is going to be 1000x better than accepting certain forms, but not bothering to tell the user up-front, and instead telling them what they did was wrong, after they try.
It's not cool for relationships; it's equally not cool, here.
You've got 9-digit and 10-digit numbers, so if you're trying for an international solution, be prepared to deal with all international separators (, \.\-\(\)\+) etc... again, why stripping is more useful, because THAT RegEx would be insane.

ASP.NET Regex to validate mobile phone number

I have an application to send TAN to users via SMS. We have already API to send SMS to a mobile phone number. Therefore, I have to make sure it's correct mobile phone number. Below is my regex:
function validateMobile(str) {
var filter = /^\+?(\d[\d-. ]+)?(\([\d-. ]+\))?[\d-. ]+\d$/;
if (!filter.test(str)) {
alert('Please provide a valid mobile phone number');
return false;
}
return true;
}
It doesn't accept characters, only number and '+' allowed. Users can enter, for example +49176xxxxxxxx or 0176xxxxxxxx (no particular country code)
But this regex is seriously flawed. Users can enter whatever numbers, e.g. 1324567982548, this regex also returns true. I thought about to check the length of the textbox, it'd work, for the time being, but still it's not a proper solution.
Is there any other better regex or way to check more concrete a mobilbe phone number?
Thanks in advance.
SOLVED
I solved this with a new regex:
var filter = /^(\+49\d{8,18}|0\d{9,18})((,\+49\d{8,18})|(,0\d{9,18}))*$/;
or as mzmm56 suggested below:
var filter = /^(?:(\+|00)(49)?)?0?1\d{2,3}\d{8}$/;
Both are equally fine.
i think that you may need to restrict the regex to mobile number format of the country you're targetting, if possible, or check the input against a variety of patterns according to different countries' mobile number formats. it also seems like your regex would match .- instead of " only number and '+' ".
anywayā€”in Germany, i believe the following regex would work, only allowing a single + at the beginning, and then nothing but numbers:
^(?:(\+|00)(49)?)?0?1\d{2,3}\d{8}$
with 0?1\d{2,3} it's taking into account that German mobile numbers may or may not start with 0, begin with 1, and are followed by another 2 numbers (in your case 76), or 3 numbers (176) if there was no leading 0.
It might be easier to to strip off all non-numeric characters (except + perhaps), then regex it, then if you need to output it, just reformat it.
Here's a regex for the phone number after non-numeric characters have been stripped:
^\+[1-9]{1}[0-9]{10}$
For more detailed info on country codes, see this post.

Check that the user is entering a time format? eg 13:00

Basically, I'd like to have an input that when blur'd, will check the input to make sure it's in the format...
[24hour] : [minutes]
So for example 13:00, or 15:30.
So I guess I have to split it up into three parts, check the first bit is between 0 and 24, then check it has the semi-colon, then check it has a number between 0 and 60.
Going more complicated than that, it'd be fantastic to have it so if the user enters 19 it'll complete it as 19:00 for example.
I am using jQuery fwiw, but regular code is fine, for example I'm using this little piece of code so far which works fine, to convert . inputs to :
tempval = $(this).val().replace(".", ":");
$(this).val(tempval);
Not sure where to start with this, if anyone could recommend me some reading that'd be fantastic, thank you!
([0-1 ]?[0-9]|2[0-3]):([0-5][0-9])
I think that's the regex you're looking for (not specifically for javascript though).
http://www.regular-expressions.info/
This site has an excellent amount of info for language-specific regular expressions! Cheers!
I suggest using masked input That way the wrong input will be prevented in the first place.
Disclaimer: I haven't used that plugin myself, just found it by keywords "masked input"
There are a bunch of widgets that already deal with time validation - try googling for "jQuery time widget" - the first result doesn't look bad.
var re = /^(\d+)(:\d+)?$/;
var match = re.match(yourstring);
Now if the match has succeeded match is an array with the matched pieces: match[0] is the whole of yourstring (you don't care about that), match[1] has the digits before the colon (if any colon, else just digits), match[2] if it exists has the colon followed by the digits after it. So now you just need to perform your numeric tests on match[1], and possibly match[2] minus the leading colon, to ensure the numbers are correct.

Categories

Resources