Skip to content

Commit

Permalink
feat(validate): expose validate function with boolean return value (#38)
Browse files Browse the repository at this point in the history
  • Loading branch information
m-mohr committed Feb 14, 2020
1 parent 43a9dc0 commit c9fd967
Show file tree
Hide file tree
Showing 4 changed files with 60 additions and 0 deletions.
10 changes: 10 additions & 0 deletions README.md
Expand Up @@ -78,6 +78,16 @@ compareVersions.compare('10.1.1', '10.2.2', '<='); // return true
compareVersions.compare('10.1.1', '10.2.2', '>='); // return false
```

### Validate version numbers

Applies the same ruleset as used before comparing version numbers and returns a boolean:

```javascript
compareVersions.validate('1.0.0-rc.1'); // return true
compareVersions.validate('1.0-rc.1'); // return false
compareVersions.validate('foo'); // return false
```

### Browser

If included directly in the browser, `compareVersions()` is available on the global window:
Expand Down
17 changes: 17 additions & 0 deletions index.d.ts
Expand Up @@ -37,6 +37,23 @@ declare const compareVersions: {
secondVersion: string,
operator: compareVersions.CompareOperator
): boolean;

/**
* Validate [semver](https://semver.org/) version strings.
*
* @param version Version number to validate
* @returns `true` if the version number is a valid semver version number, `false` otherwise.
*
* @example
* ```
* compareVersions.validate('1.0.0-rc.1'); // return true
* compareVersions.validate('1.0-rc.1'); // return false
* compareVersions.validate('foo'); // return false
* ```
*/
validate(
version: string
): boolean;
};

export = compareVersions;
4 changes: 4 additions & 0 deletions index.js
Expand Up @@ -97,6 +97,10 @@
}
}

compareVersions.validate = function(version) {
return typeof version === 'string' && semver.test(version);
}

compareVersions.compare = function (v1, v2, operator) {
// Validate operator
validateOperator(operator);
Expand Down
29 changes: 29 additions & 0 deletions test/validate.js
@@ -0,0 +1,29 @@
const assert = require('assert');
const compare = require('..');

describe('validate versions', () => {
[
[undefined, false],
[null, false],
[42, false],
[{}, false],
[[], false],
[() => undefined, false],
['6.3.', false],
['1.2.3a', false],
['1.2.-3a', false],
['v1.0.0', true],
['01.0.0', true],
['1.0.x', true],
['1.0.0-rc.1', true],
['1.0.0-alpha', true],
['1.0.0-build.3928', true],
['1.0.0+20130313144700', true],
['1.2.3.100', true],
['2020', true]
].forEach(([v, expected]) => {
it(`${v}`, () => {
assert.equal(compare.validate(v), expected)
});
});
});

0 comments on commit c9fd967

Please sign in to comment.