Ionic
Ionic

Reputation: 193

what should be the RegExp for app version validation?

I am stuck in one RegExp where I need to validate app version for app store and play-store. I have tried several RegExp but none of them is useful for me. Here are the example that pass the test

App version up-to 2-3 decimal point

1.0 // pass

1.0.0 // pass

1.0.0.0 // fail

a.0 // fail

1 // pass

I found one RegExp [0-9]+\.[0-9]+\.[0-9]+\.[0-9]+ but this will only be valid when I have enter 4 decimal points. I don't know how to modify this.

Please help.

Upvotes: 4

Views: 2548

Answers (5)

Vlad Prykhodskyi
Vlad Prykhodskyi

Reputation: 1

I found this one useful for my case

/^\d+(?:\.\d+){2}$/gm

This will match only the versions made of 3 dots and numbers only

Example:

1.2.3 - matches

21.5.3 - matches

1.2.3.4 - fails

1.a.4 - fails

Upvotes: 0

Oram
Oram

Reputation: 1673

^\d+(?:\.\d+){0,2}$

This will start with a number (\d is the same as [0-9]) and then zero or more decimal point followed by more numbers.

var input = [
  "1.0", // pass
  "1.0.0", // pass
  "1.0.0.0", // fail
  "a.0", // fail
  "1", // pass
  "1.",
  "1.a"
]

var regex = /^\d+(?:\.\d+){0,2}$/;

input.forEach(function(item) {
  console.log(item, regex.test(item));
});

If you want to limit the number of digits, you can change the \d+ into \d{n,m} (replace n with the minimum number of digits and m with the maximum number of digits).

The + is the same as {1,} which means "one or more".

Upvotes: 4

Maheer Ali
Maheer Ali

Reputation: 36574

You can try the following regex

let reg = /^[0-9]((\.)[0-9]){0,2}$/

console.log(reg.test('1.0')) //true
console.log(reg.test('1.1.0')) //true
console.log(reg.test('1')) //true

console.log(reg.test('1.')) //false
console.log(reg.test('1.a')) //false
console.log(reg.test('1.1.1.1')) //false

Upvotes: 5

Kamil Kiełczewski
Kamil Kiełczewski

Reputation: 92467

Try

^(\d+\.){0,2}\d+$

let versions= [
  "1.0",
  "1.0.0",
  "1.0.0.0",
  "a.0",
  "1",
]

versions.forEach(v=> console.log(v, /^(\d+\.){0,2}\d+$/.test(v) ) );

Upvotes: 3

Kishan Oza
Kishan Oza

Reputation: 1735

you have mentioned up to 2-3 decimal then the RegExp must be this

^(\d+\.)?(\d+\.)?(\d+\.)?(\*|\d+)?$

Upvotes: 5

Related Questions