monkeylee
monkeylee

Reputation: 965

jquery validation regex for digits with hyphens

Can someone provide a regex that only allows digits and optionally hyphens

I have got as far as phone_number.match(/[0-9-]/); but with no luck

Upvotes: 2

Views: 7310

Answers (8)

I AM GROOT
I AM GROOT

Reputation: 291

I recently developed a regex pattern for my assignment which exactly matches 999-999-9999.

/^\d{3}-{1}\d{3}-{1}\d{4}$/

^ asserts position at start of a line
\d matches a digit (equivalent to [0-9])
{3} matches the previous token exactly 3 times
- matches the character - with index 4510 (2D16 or 558) literally (case sensitive)
{1} matches the previous token exactly one time (meaningless quantifier)
\d matches a digit (equivalent to [0-9])
{3} matches the previous token exactly 3 times
- matches the character - with index 4510 (2D16 or 558) literally (case sensitive)
{1} matches the previous token exactly one time (meaningless quantifier)
\d matches a digit (equivalent to [0-9])
{4} matches the previous token exactly 4 times
$ asserts position at the end of a line

Upvotes: 0

Sarbasish Mishra
Sarbasish Mishra

Reputation: 156

Here is the solution for a input with hyphens

$('input[type="tel"]').keyup(function() {
  this.value = this.value
    .match(/\d*/g).join('')
    .match(/(\d{0,3})(\d{0,3})(\d{0,4})/).slice(1).join('-')
    .replace(/-*$/g, '');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="tel"></input>

Upvotes: 0

Manu R S
Manu R S

Reputation: 970

Check this out...

var phoneno = /^+?[0-9]+(-[0-9]+)*$/;

Ans +954-555-1234

Upvotes: 0

mkmkmk
mkmkmk

Reputation: 71

What you're describing is used in the jquery validate plugin http://docs.jquery.com/Plugins/Validation/CustomMethods/phoneUS

^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$

I came here searching for something similar and found what I needed at http://regexlib.com/ they have a great collection of expressions as well as a helpful cheat sheet.

Upvotes: 2

TimCodes.NET
TimCodes.NET

Reputation: 4689

Try this out...

/^[0-9]+(\-[0-9]+)*$/

Not phone numbers, but what you wanted from the comments

Upvotes: 0

markijbema
markijbema

Reputation: 4055

The following matches numbers interspersed with dashes, but not double dashes:

/^\d+(-\d+)*$/

Upvotes: 6

melhosseiny
melhosseiny

Reputation: 10154

/^\w*-?\w*-?\w*$/
  • \w* Alphanumeric character repeated 0 or many times.
  • -? Optional hyphen.

Upvotes: 0

CoolEsh
CoolEsh

Reputation: 3154

Try this plugin: Masked Input jQuery plugin. It allows to make own masks and simplifies input for user.

Upvotes: 0

Related Questions