How to use the validRange function from semver

Find comprehensive JavaScript semver.validRange code examples handpicked from public code repositorys.

semver.validRange is a function that checks if a given string is a valid semantic versioning range.

285
286
287
288
289
290
291
292
293
294
// try tag first
let realPkgVersion = distTags[spec];

if (!realPkgVersion) {
  const version = semver.valid(spec);
  const range = semver.validRange(spec, true);
  if (semver.satisfies(distTags.latest, spec)) {
    realPkgVersion = distTags.latest;
  } else if (version) {
    // use the valid version
fork icon64
star icon476
watch icon17

61
62
63
64
65
66
67
68
69
70
runNpmShow(dep) {
  const depSplit = dep.split('@');
  const [depName, depVersion] = dep.charAt(0) !== '@' ? depSplit : [`@${depSplit[1]}`, depSplit[2]];

  if (depVersion) {
    const depRange = semver.validRange(depVersion) || '';
    const specifiedVersions = depRange.replace(/[~^<>=]+/g, '').split(' ');
    const operators = depRange.match(/[~^<>=]+/g) || ['=='];

    return new Promise((resolve) => {
fork icon8
star icon20
watch icon2

How does semver.validRange work?

semver.validRange is a function provided by the SemVer library that checks if a given string is a valid semantic versioning range.

Semantic versioning (or SemVer) is a versioning system for software that consists of three parts: a major version, a minor version, and a patch version, separated by dots (e.g., 1.2.3). Semantic versioning ranges allow developers to specify a range of compatible versions for a package, rather than a specific version number.

To use semver.validRange, you pass a string as an argument that represents a SemVer range. The function will return null if the string is not a valid SemVer range, or a normalized string representing the range if it is valid.

For example, if you pass the string ">=1.2.3 <1.3.0" to semver.validRange, it will return the normalized string ">=1.2.3 <1.3.0".

The semver.validRange function is often used by package managers or other tools that need to parse SemVer ranges, to ensure that the ranges specified by users are valid and can be processed correctly.

6
7
8
9
10
11
12
13
14
15

const semverRangeExtension = {
  base: Joi.string(),
  type: 'semverRange',
  validate: function (value, { error }) {
    return semver.validRange(value) ? { value } : { errors: error(`${extensionName}.valid`) }
  },
  messages: {
    [`${extensionName}.valid`]: '{{#label}} needs to be a valid semver range'
  }
fork icon4
star icon7
watch icon3

10
11
12
13
14
15
16
17
18
19
  .map(release => release.tag_name.substring(1)) // remove the "v" in the version
  .sort((a, b) => semver.rcompare(a, b)); // sort via semver

// Test version constraint
// "latest" and "next" will return invalid but that's ok because we check it explicitly
const validVersionConstraint = semver.validRange(versionConstraint, { includePrerelease: false, loose: true });

var version
// Include prelease versions, like v1.0.0-rc1 or v1.0.1-dev
if (versionConstraint == 'next') {
fork icon4
star icon6
watch icon0

Ai Example

1
2
3
4
5
6
7
8
9
const semver = require("semver");

const range1 = ">=1.2.3 <1.3.0";
const range2 = "1.x";
const range3 = "latest";

console.log(semver.validRange(range1)); // ">-1.2.3 <1.3.0"
console.log(semver.validRange(range2)); // ">=1.0.0 <2.0.0-0"
console.log(semver.validRange(range3)); // ">=0.0.0"

In this example, we are using semver.validRange to check if the strings range1, range2, and range3 are valid SemVer ranges. The function returns a normalized string representing the range if it is valid, or null if it is not valid. In this case, range1 is a valid range and returns ">=1.2.3 <1.3.0". range2 is also a valid range and returns ">=1.0.0 <2.0.0-0". range3, however, is not a valid range and returns null.

35
36
37
38
39
40
41
42
43
44
if (body == null) return callback()

const resolved = {
  version: body.version,
  resolved: body.dist.tarball,
  from: semver.validRange(body.version)
}

if (body.dependencies && Object.keys(body.dependencies).length) {
  resolved.dependencies = body.dependencies
fork icon5
star icon5
watch icon21

55
56
57
58
59
60
61
62
63
64
    // We add minors like this because a minor beta is still compatible with a minor non-beta.
    newRange = range;
    for (let minor = 0; minor < 20; minor++) {
        newRange += ` || ^${major}.${minor}.0-alpha.0 `;
    }
    return semver.validRange(newRange) || range;
}
exports.angularMajorCompatGuarantee = angularMajorCompatGuarantee;
// This is a map of packageGroupName to range extending function. If it isn't found, the range is
// kept the same.
fork icon1
star icon0
watch icon0

98
99
100
101
102
103
104
105
106
107
108
    for (var _len2 = arguments.length, ranges = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
        ranges[_key2] = arguments[_key2];
    }


    return ranges.reduce(function (result, range) {
        var validRange = semver.validRange(range);
        var validRanges = validRange.split(regex.whitespace);
        return union(result, validRanges);
    }, []);
}
fork icon0
star icon0
watch icon1

874
875
876
877
878
879
880
881
882
883
884
885
 */
function getDefaultVersion(filename) {
    const info = getPackageJson(filename)
    const nodeVersion = info && info.engines && info.engines.node


    return semver.validRange(nodeVersion) || DEFAULT_VERSION
}


/**
 * Gets values of the `ignores` option.
fork icon0
star icon0
watch icon1

+ 15 other calls in file

413
414
415
416
417
418
419
420
421
422
// no save spec for registry components as we save based on the fetched
// version, not on the argument so this can't compute that.
res.saveSpec = null
res.fetchSpec = spec
const version = semver.valid(spec, true)
const range = semver.validRange(spec, true)
if (version) {
  res.type = 'version'
} else if (range) {
  res.type = 'range'
fork icon0
star icon0
watch icon1