Skip to content

isValid to validate timestamp #29

@loretoparisi

Description

@loretoparisi

The isValid works ok, but does not take in account the validation of timestamp and randomness separately, hence I suggest this enhancement to validate the timestamp part:

function isValid(id) {
    var valid = (
        typeof id === "string" &&
        id.length === TIME_LEN + RANDOM_LEN &&
        id
            .toUpperCase()
            .split("")
            .every(char => ENCODING.indexOf(char) !== -1)
    );
    try { valid &= isTimestamp(decodeTime(id)); } catch(error) { valid = false }
    return valid;
}

where decodeTime is ulid.decodeTime and utils are

function isNumeric(n) {
    return !isNaN(parseFloat(n)) && isFinite(n);
}
function isTimestamp(_timestamp) {
    const newTimestamp = new Date(_timestamp).getTime();
    return isNumeric(newTimestamp);
}

This should be enough to guaratee that both ulid and monotonic are valid ulid with timestamp and randomness information.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions