Shannon Hochkins
Shannon Hochkins

Reputation: 12175

Restrict to either all characters or all numbers?

Let's say I want to restrict a user to enter a suburb or a postcode but not both,

I want 'suburb' to pass as it's all alpha characters, I want '1234' to pass as it's all numeric, but I can't figure out how to map and either or inside a regex.

Here's what I've tried.

var string = 'word';

var resultA = !(string.match(/^[a-z|0-9]+$/i));

alert(resultA);

So I need:

'word'  => true
'1234'  => true
'word word' => true,
'word 123' => false,
'word2' => false

When it runs through the expression.

Upvotes: 1

Views: 45

Answers (2)

zzzzBov
zzzzBov

Reputation: 179046

When developers ask how to overcomplicate their regular expressions, I usually recommend that they take a step back and just write some code, and throw in regex for the parts they can formalize well.

You asked how to determine if a string is entirely alpha characters or entirely numbers.

A regex to detect all alphabetic characters is

/^[a-z]*$/i

A regex to detect all numeric characters is

/^\d*$/

Combining them is simply:

function valid(str) {
  return /^[a-z]*$/i.test(str) || /^\d*$/.test(str);
}

Now if you want to combine it all into a single regular expression you just have to use the | regular expression operation:

function valid(str) {
  return /^[a-z]*$|^\d*$/i.test(str);
}

This can of course be simplified if you use a grouping operator:

/^([a-z]*|\d*)$/i

don't simplify it. It's easier to read and easier to reason about regular expressions when they're shorter and match simpler patterns. Use more small regular expressions, rather than fewer longer regular expressions, even if the code could be made shorter. Future you will thank past you for making the code easier to understand.

Upvotes: 0

anubhava
anubhava

Reputation: 784898

You can use this regex to match either alphabets or digits in input:

var resultA = /^([A-Za-z]+|[0-9]+)$/.test(string);

Upvotes: 3

Related Questions