diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md index feab2fa77..799e41348 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.md +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -14,6 +14,9 @@ A clear and concise description of what the bug is. **Examples** If applicable, add screenshots to help explain your problem. +**Reproductions** +If applicable, provide a reproduction on platforms like [runkit](npm.runkit.com/validator) + **Additional context** Validator.js version: Node.js version: diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 21686d855..b4e532908 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -9,7 +9,7 @@ jobs: runs-on: ubuntu-20.04 strategy: matrix: - node-version: [14, 12, 10, 8, 6] + node-version: [20, 18, 16, 14, 12, 10, 8, 6] name: Run tests on Node.js ${{ matrix.node-version }} steps: - name: Setup Node.js ${{ matrix.node-version }} @@ -20,10 +20,10 @@ jobs: - name: Checkout repository uses: actions/checkout@v2 - name: Install dependencies - run: npm install + run: npm install --legacy-peer-deps - name: Run tests run: npm test - - if: matrix.node-version == 14 + - if: matrix.node-version == 20 name: Send coverage info to Codecov uses: codecov/codecov-action@v1 with: diff --git a/.github/workflows/npm-publish.yml b/.github/workflows/npm-publish.yml index b4b62f1b9..ccc202ca2 100644 --- a/.github/workflows/npm-publish.yml +++ b/.github/workflows/npm-publish.yml @@ -5,20 +5,23 @@ on: jobs: publish: runs-on: ubuntu-20.04 + permissions: + contents: read + id-token: write steps: - - name: Setup Node.js 14 - uses: actions/setup-node@v2-beta + - name: Setup Node.js 18 + uses: actions/setup-node@v3 with: - node-version: 14 + node-version: 18 check-latest: true registry-url: https://registry.npmjs.org/ - name: Checkout Repository - uses: actions/checkout@v2 + uses: actions/checkout@v3 - name: Install Dependencies run: npm install - name: Run Tests run: npm test - name: Publish Package to NPM Registry - run: npm publish + run: npm publish --provenance env: NODE_AUTH_TOKEN: ${{secrets.NPM_SECRET}} diff --git a/CHANGELOG.md b/CHANGELOG.md index 8d27cf979..236fe7ca5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,91 @@ +# 13.15.0 + +### New Features / Validators + +- [#2399](https://github.com/validatorjs/validator.js/pull/2399) `isISO31661Numeric` @RobinvanderVliet +- [#2294](https://github.com/validatorjs/validator.js/pull/2294) `isULID` @arafatkn +- [#2215](https://github.com/validatorjs/validator.js/pull/2215) `isISO15924` @xDivisionByZerox + +### Fixes, New Locales and Enhancements + +- `isMobilePhone` + - [#2395](https://github.com/validatorjs/validator.js/pull/2395) add `es-GT` locale @ignaciosuarezquilis + - [#1971](https://github.com/validatorjs/validator.js/pull/1971) improve `en-GB` locale @ihmpavel + - [#2359](https://github.com/validatorjs/validator.js/pull/2359) improve `uk-UA` locale @arttiger + - [#2350](https://github.com/validatorjs/validator.js/pull/2350) improve `ky-KG` locale @sadraliev + - [#2482](https://github.com/validatorjs/validator.js/pull/2482) improve `en-ZM` locale @sonikishan + - [#2362](https://github.com/validatorjs/validator.js/pull/2362) improve `en-GH` locale @NanaAb-116 + - [#2500](https://github.com/validatorjs/validator.js/pull/2500) add `mk-MK` locale @eshward95 + - [#2534](https://github.com/validatorjs/validator.js/pull/2534) improve `sq-AL` locale @nichoola +- [#2406](https://github.com/validatorjs/validator.js/pull/2406) `isBtcAddress` support all address formats and testnets @madoke +- [#2339](https://github.com/validatorjs/validator.js/pull/2339) `isIBAN` improve `VG` regex @ST-DDT +- [#2332](https://github.com/validatorjs/validator.js/pull/2332) `isISO4217` update currency codes @cbodtorf +- [#2291](https://github.com/validatorjs/validator.js/pull/2291) `isIdentityCard` add `PK` locale @Daniyal-Qureshi +- [#2414](https://github.com/validatorjs/validator.js/pull/2414) `isEmail` fix blacklist_chars @keshavlingala +- [#2416](https://github.com/validatorjs/validator.js/pull/2416) `isInt`/`isFloat` handle undefined and null values @Daniyal-Qureshi +- [#2415](https://github.com/validatorjs/validator.js/pull/2415) `isPostalCode` add `CO` locale @jorgevrgs +- [#2404](https://github.com/validatorjs/validator.js/pull/2404) `isPassportNumber` export `passportNumberLocales` @derekparnell +- [#2029](https://github.com/validatorjs/validator.js/pull/2029) `isRgbColor` add `allowSpaces` option @a-h-i +- [#2421](https://github.com/validatorjs/validator.js/pull/2421) `isUUID` require valid variant field and require RFC9562 UUID in version `all` @broofa +- [#2439](https://github.com/validatorjs/validator.js/pull/2439) `isURL` add `max_allowed_length` option @pinkiesky +- [#2437](https://github.com/validatorjs/validator.js/pull/2437) `isEmail` reject starting with double quotes @code0emperor +- [#2333](https://github.com/validatorjs/validator.js/pull/2333) `isLicensePlate` add `en-SG` locale @Sabarinathan07 +- [#2441](https://github.com/validatorjs/validator.js/pull/2441) `normalizeEmail` add `yandex_convert_yandexru` option @AayushGH +- [#2443](https://github.com/validatorjs/validator.js/pull/2443) `isDate` return false instead of Error in certain cases @pano9000 +- [#2474](https://github.com/validatorjs/validator.js/pull/2474) `isLength` add `discreteLengths` option @Suven-p +- [#2481](https://github.com/validatorjs/validator.js/pull/2481) `isDate` disallow mismatching length in `strictMode` @sonikishan +- [#2492](https://github.com/validatorjs/validator.js/pull/2492) `isISO6346` set check digit to 0 if remainder is 10 @joelcuy +- [#2493](https://github.com/validatorjs/validator.js/pull/2493) `isPostalCode` improve `BR` locale @ticmaisdev +- [#2494](https://github.com/validatorjs/validator.js/pull/2494) `isEmail` allow regexp in `host_whitelist` and `host_blacklist` @weikangchia +- [#2518](https://github.com/validatorjs/validator.js/pull/2518) `isIBAN` improve `IE`/`PS` regex @Tarasz57 +- **Doc fixes and others:** + - [#2402](https://github.com/validatorjs/validator.js/pull/2402) @BibhushanKarki + - [#2394](https://github.com/validatorjs/validator.js/pull/2394) @RobinvanderVliet + - [#1732](https://github.com/validatorjs/validator.js/pull/1732) @alguerocode + - [#2413](https://github.com/validatorjs/validator.js/pull/2413) @rubiin + - [#2408](https://github.com/validatorjs/validator.js/pull/2408) @profnandaa + - [#2411](https://github.com/validatorjs/validator.js/pull/2411) @rubiin + - [#2325](https://github.com/validatorjs/validator.js/pull/2325) @ovarn + - [#2418](https://github.com/validatorjs/validator.js/pull/2418) @ihmpavel + - [#2323](https://github.com/validatorjs/validator.js/pull/2323) @ovarn + - [#2423](https://github.com/validatorjs/validator.js/pull/2423) @rubiin + - [#2409](https://github.com/validatorjs/validator.js/pull/2409) @profnandaa + - [#2442](https://github.com/validatorjs/validator.js/pull/2442) @pano9000 + +# 13.12.0 + +### New Features / Validators + +- [#2143](https://github.com/validatorjs/validator.js/pull/2143) `isAbaRouting` @songyuew + +### Fixes, New Locales and Enhancements + +- [#2207](https://github.com/validatorjs/validator.js/pull/2207) `isLicensePlate` add Pakistani `en-PK` locale @anasshakil +- [#2208](https://github.com/validatorjs/validator.js/issues/2208) `isPort` fix invalid leading zeros @anasshakil +- [#2224](https://github.com/validatorjs/validator.js/pull/2224) `isTaxID` added Argentina `es-AR` locale @estefrare +- [#2257](https://github.com/validatorjs/validator.js/pull/2257) `isDate` timezone offset fix @tomaspanek +- [#2265](https://github.com/validatorjs/validator.js/pull/2265) `isPassportNumber` added `ZA` locale @GMorris-professional +- `isMobilePhone`: + - [#2267](https://github.com/validatorjs/validator.js/pull/2267) added `en-MW` locale @SimranSiddiqui + - [#2140](https://github.com/validatorjs/validator.js/pull/2140) fix `am-AM` locale @AlexKrupko +- [#2271](https://github.com/validatorjs/validator.js/pull/2271) `isPostalAddress` fix `NL` locale @RobinvanderVliet +- [#2273](https://github.com/validatorjs/validator.js/pull/2273) `isISO4217` add `SLE` currency @urg +- [#2278](https://github.com/validatorjs/validator.js/pull/2278) `isStrongPassword` fix symbolRegex to include `\` @nandavikas +- [#2279](https://github.com/validatorjs/validator.js/pull/2279) `isVAT` fixed `KZ` locale @MatthieuLemoine +- [#2285](https://github.com/validatorjs/validator.js/pull/2285) `isAlpha`, `isAlphanumeric` added `eo` locale @RobinvanderVliet +- [#2320](https://github.com/validatorjs/validator.js/pull/2320) `isIBAN` add Algeria `DZ` locale @thibault-lr +- [#2343](https://github.com/validatorjs/validator.js/pull/2343) `isVAT`improve `AU` locale @matthewberryman +- [#2345](https://github.com/validatorjs/validator.js/pull/2345) `isUUID` add support for v7 @ruscon +- [#2358](https://github.com/validatorjs/validator.js/pull/2358) `isTaxID` add Ukraine `uk-UA` locale @arttiger +- [#2381](https://github.com/validatorjs/validator.js/pull/2381) `isDate` disallow hiphen before year @Sumit-tech-joshi +- **Doc fixes and others:** + - [#2276](https://github.com/validatorjs/validator.js/pull/2276) @meyfa + - [#2341](https://github.com/validatorjs/validator.js/pull/2341) @WikiRik + - [#2364](https://github.com/validatorjs/validator.js/pull/2364) @rubiin + - [#2368](https://github.com/validatorjs/validator.js/pull/2368) @ZhulinskiiDanil + - [#2371](https://github.com/validatorjs/validator.js/pull/2371) @devmanbud + - [#2386](https://github.com/validatorjs/validator.js/pull/2386) @alinaghale88 + # 13.11.0 ### New Features / Validators diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 000000000..c7da04163 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,37 @@ +# Contributing to validator.js +Welcome to validator.js repository!! We appreciate your interest in contributing to this open library and for helping our community grow. + +## How to Contribute +### Code Contribution +In general, we follow the "fork-and-pull" Git workflow. + +1. [Fork](https://docs.github.com/en/get-started/exploring-projects-on-github/contributing-to-a-project) the repository on GitHub +2. Clone the project to your local machine +3. Work on your fork + * Make your changes and additions + - Most of your changes should be focused on src/ and test/ folders and/or [README.md](https://github.com/validatorjs/validator.js/blob/master/README.md). + - Files such as validator.js, validator.min.js and files in lib/ folder are autogenerated when running tests (npm test) and need not to be changed **manually**. + * Change or add tests if needed + * Run tests and make sure they pass + * Add changes to README.md if needed +4. Commit changes to your own branch +5. **Make sure** you merge the latest from "upstream" and resolve conflicts if there is any +6. Repeat step 3(3) above +7. Push your work back up to your fork +8. Submit a Pull request so that we can review your changes + +#### Run Tests +Tests are using mocha. To run the tests use: + +```sh +$ npm test +``` + +### Financial Contribution +We welcome financial contributions on our [open collective](https://opencollective.com/validatorjs). + +You can opt to become a [backer](https://opencollective.com/validatorjs#backer) or a [sponsor](https://opencollective.com/validatorjs#sponsor) and help our project sustain over time. + +Thank you to the people who have already contributed: + + \ No newline at end of file diff --git a/README.md b/README.md index e00b7cfac..8ec51aaab 100644 --- a/README.md +++ b/README.md @@ -1,12 +1,13 @@ # validator.js + [![NPM version][npm-image]][npm-url] [![CI][ci-image]][ci-url] [![Coverage][codecov-image]][codecov-url] [![Downloads][downloads-image]][npm-url] [![Backers on Open Collective](https://opencollective.com/validatorjs/backers/badge.svg)](#backers) [![Sponsors on Open Collective](https://opencollective.com/validatorjs/sponsors/badge.svg)](#sponsors) +[![License](https://img.shields.io/badge/License-MIT-red.svg)](https://github.com/alguerocode/validator.js/blob/master/LICENSE) [![Gitter][gitter-image]][gitter-url] -[![Disclose a vulnerability][huntr-image]][huntr-url] A library of string validators and sanitizers. @@ -21,32 +22,38 @@ Passing anything other than a string will result in an error. ### Server-side usage -Install the library with `npm install validator` +Install the `validator` package as: + +```sh +npm i validator +yarn add validator +pnpm i validator +``` #### No ES6 ```javascript -var validator = require('validator'); +var validator = require("validator"); -validator.isEmail('foo@bar.com'); //=> true +validator.isEmail("foo@bar.com"); //=> true ``` #### ES6 ```javascript -import validator from 'validator'; +import validator from "validator"; ``` Or, import only a subset of the library: ```javascript -import isEmail from 'validator/lib/isEmail'; +import isEmail from "validator/lib/isEmail"; ``` #### Tree-shakeable ES imports ```javascript -import isEmail from 'validator/es/lib/isEmail'; +import isEmail from "validator/es/lib/isEmail"; ``` ### Client-side usage @@ -56,7 +63,7 @@ The library can be loaded either as a standalone script, or through an [AMD][amd ```html ``` @@ -72,128 +79,122 @@ CDN ``` -## Contributors - -[Become a backer](https://opencollective.com/validatorjs#backer) - -[Become a sponsor](https://opencollective.com/validatorjs#sponsor) - -Thank you to the people who have already contributed: - - - ## Validators Here is a list of the validators currently available. -Validator | Description ---------------------------------------- | -------------------------------------- -**contains(str, seed [, options])** | check if the string contains the seed.

`options` is an object that defaults to `{ ignoreCase: false, minOccurrences: 1 }`.
Options:
`ignoreCase`: Ignore case when doing comparison, default false.
`minOccurences`: Minimum number of occurrences for the seed in the string. Defaults to 1. -**equals(str, comparison)** | check if the string matches the comparison. -**isAfter(str [, options])** | check if the string is a date that is after the specified date.

`options` is an object that defaults to `{ comparisonDate: Date().toString() }`.
**Options:**
`comparisonDate`: Date to compare to. Defaults to `Date().toString()` (now). -**isAlpha(str [, locale, options])** | check if the string contains only letters (a-zA-Z).

`locale` is one of `['ar', 'ar-AE', 'ar-BH', 'ar-DZ', 'ar-EG', 'ar-IQ', 'ar-JO', 'ar-KW', 'ar-LB', 'ar-LY', 'ar-MA', 'ar-QA', 'ar-QM', 'ar-SA', 'ar-SD', 'ar-SY', 'ar-TN', 'ar-YE', 'bg-BG', 'bn', 'cs-CZ', 'da-DK', 'de-DE', 'el-GR', 'en-AU', 'en-GB', 'en-HK', 'en-IN', 'en-NZ', 'en-US', 'en-ZA', 'en-ZM', 'es-ES', 'fa-IR', 'fi-FI', 'fr-CA', 'fr-FR', 'he', 'hi-IN', 'hu-HU', 'it-IT', 'kk-KZ', 'ko-KR', 'ja-JP', 'ku-IQ', 'nb-NO', 'nl-NL', 'nn-NO', 'pl-PL', 'pt-BR', 'pt-PT', 'ru-RU', 'si-LK', 'sl-SI', 'sk-SK', 'sr-RS', 'sr-RS@latin', 'sv-SE', 'th-TH', 'tr-TR', 'uk-UA']` and defaults to `en-US`. Locale list is `validator.isAlphaLocales`. `options` is an optional object that can be supplied with the following key(s): `ignore` which can either be a String or RegExp of characters to be ignored e.g. " -" will ignore spaces and -'s. -**isAlphanumeric(str [, locale, options])** | check if the string contains only letters and numbers (a-zA-Z0-9).

`locale` is one of `['ar', 'ar-AE', 'ar-BH', 'ar-DZ', 'ar-EG', 'ar-IQ', 'ar-JO', 'ar-KW', 'ar-LB', 'ar-LY', 'ar-MA', 'ar-QA', 'ar-QM', 'ar-SA', 'ar-SD', 'ar-SY', 'ar-TN', 'ar-YE', 'bn', 'bg-BG', 'cs-CZ', 'da-DK', 'de-DE', 'el-GR', 'en-AU', 'en-GB', 'en-HK', 'en-IN', 'en-NZ', 'en-US', 'en-ZA', 'en-ZM', 'es-ES', 'fa-IR', 'fi-FI', 'fr-CA', 'fr-FR', 'he', 'hi-IN', 'hu-HU', 'it-IT', 'kk-KZ', 'ko-KR', 'ja-JP','ku-IQ', 'nb-NO', 'nl-NL', 'nn-NO', 'pl-PL', 'pt-BR', 'pt-PT', 'ru-RU', 'si-LK', 'sl-SI', 'sk-SK', 'sr-RS', 'sr-RS@latin', 'sv-SE', 'th-TH', 'tr-TR', 'uk-UA']`) and defaults to `en-US`. Locale list is `validator.isAlphanumericLocales`. `options` is an optional object that can be supplied with the following key(s): `ignore` which can either be a String or RegExp of characters to be ignored e.g. " -" will ignore spaces and -'s. -**isAscii(str)** | check if the string contains ASCII chars only. -**isBase32(str [, options])** | check if the string is base32 encoded. `options` is optional and defaults to `{ crockford: false }`.
When `crockford` is true it tests the given base32 encoded string using [Crockford's base32 alternative][Crockford Base32]. -**isBase58(str)** | check if the string is base58 encoded. -**isBase64(str [, options])** | check if the string is base64 encoded. `options` is optional and defaults to `{ urlSafe: false }`
when `urlSafe` is true it tests the given base64 encoded string is [url safe][Base64 URL Safe]. -**isBefore(str [, date])** | check if the string is a date that is before the specified date. -**isBIC(str)** | check if the string is a BIC (Bank Identification Code) or SWIFT code. -**isBoolean(str [, options])** | check if the string is a boolean.
`options` is an object which defaults to `{ loose: false }`. If `loose` is is set to false, the validator will strictly match ['true', 'false', '0', '1']. If `loose` is set to true, the validator will also match 'yes', 'no', and will match a valid boolean string of any case. (e.g.: ['true', 'True', 'TRUE']). -**isBtcAddress(str)** | check if the string is a valid BTC address. -**isByteLength(str [, options])** | check if the string's length (in UTF-8 bytes) falls in a range.

`options` is an object which defaults to `{ min: 0, max: undefined }`. -**isCreditCard(str [, options])** | check if the string is a credit card number.

`options` is an optional object that can be supplied with the following key(s): `provider` is an optional key whose value should be a string, and defines the company issuing the credit card. Valid values include `['amex', 'dinersclub', 'discover', 'jcb', 'mastercard', 'unionpay', 'visa']` or blank will check for any provider. -**isCurrency(str [, options])** | check if the string is a valid currency amount.

`options` is an object which defaults to `{ symbol: '$', require_symbol: false, allow_space_after_symbol: false, symbol_after_digits: false, allow_negatives: true, parens_for_negatives: false, negative_sign_before_digits: false, negative_sign_after_digits: false, allow_negative_sign_placeholder: false, thousands_separator: ',', decimal_separator: '.', allow_decimal: true, require_decimal: false, digits_after_decimal: [2], allow_space_after_digits: false }`.
**Note:** The array `digits_after_decimal` is filled with the exact number of digits allowed not a range, for example a range 1 to 3 will be given as [1, 2, 3]. -**isDataURI(str)** | check if the string is a [data uri format][Data URI Format]. -**isDate(str [, options])** | check if the string is a valid date. e.g. [`2002-07-15`, new Date()].

`options` is an object which can contain the keys `format`, `strictMode` and/or `delimiters`.

`format` is a string and defaults to `YYYY/MM/DD`.

`strictMode` is a boolean and defaults to `false`. If `strictMode` is set to true, the validator will reject strings different from `format`.

`delimiters` is an array of allowed date delimiters and defaults to `['/', '-']`. -**isDecimal(str [, options])** | check if the string represents a decimal number, such as 0.1, .3, 1.1, 1.00003, 4.0, etc.

`options` is an object which defaults to `{force_decimal: false, decimal_digits: '1,', locale: 'en-US'}`.

`locale` determines the decimal separator and is one of `['ar', 'ar-AE', 'ar-BH', 'ar-DZ', 'ar-EG', 'ar-IQ', 'ar-JO', 'ar-KW', 'ar-LB', 'ar-LY', 'ar-MA', 'ar-QA', 'ar-QM', 'ar-SA', 'ar-SD', 'ar-SY', 'ar-TN', 'ar-YE', 'bg-BG', 'cs-CZ', 'da-DK', 'de-DE', 'el-GR', 'en-AU', 'en-GB', 'en-HK', 'en-IN', 'en-NZ', 'en-US', 'en-ZA', 'en-ZM', 'es-ES', 'fa', 'fa-AF', 'fa-IR', 'fr-FR', 'fr-CA', 'hu-HU', 'id-ID', 'it-IT', 'ku-IQ', 'nb-NO', 'nl-NL', 'nn-NO', 'pl-PL', 'pl-Pl', 'pt-BR', 'pt-PT', 'ru-RU', 'sl-SI', 'sr-RS', 'sr-RS@latin', 'sv-SE', 'tr-TR', 'uk-UA', 'vi-VN']`.
**Note:** `decimal_digits` is given as a range like '1,3', a specific value like '3' or min like '1,'. -**isDivisibleBy(str, number)** | check if the string is a number that is divisible by another. -**isEAN(str)** | check if the string is an [EAN (European Article Number)][European Article Number]. -**isEmail(str [, options])** | check if the string is an email.

`options` is an object which defaults to `{ allow_display_name: false, require_display_name: false, allow_utf8_local_part: true, require_tld: true, allow_ip_domain: false, allow_underscores: false, domain_specific_validation: false, blacklisted_chars: '', host_blacklist: [] }`. If `allow_display_name` is set to true, the validator will also match `Display Name `. If `require_display_name` is set to true, the validator will reject strings without the format `Display Name `. If `allow_utf8_local_part` is set to false, the validator will not allow any non-English UTF8 character in email address' local part. If `require_tld` is set to false, email addresses without a TLD in their domain will also be matched. If `ignore_max_length` is set to true, the validator will not check for the standard max length of an email. If `allow_ip_domain` is set to true, the validator will allow IP addresses in the host part. If `domain_specific_validation` is true, some additional validation will be enabled, e.g. disallowing certain syntactically valid email addresses that are rejected by Gmail. If `blacklisted_chars` receives a string, then the validator will reject emails that include any of the characters in the string, in the name part. If `host_blacklist` is set to an array of strings and the part of the email after the `@` symbol matches one of the strings defined in it, the validation fails. If `host_whitelist` is set to an array of strings and the part of the email after the `@` symbol matches none of the strings defined in it, the validation fails. -**isEmpty(str [, options])** | check if the string has a length of zero.

`options` is an object which defaults to `{ ignore_whitespace: false }`. -**isEthereumAddress(str)** | check if the string is an [Ethereum][Ethereum] address. Does not validate address checksums. -**isFloat(str [, options])** | check if the string is a float.

`options` is an object which can contain the keys `min`, `max`, `gt`, and/or `lt` to validate the float is within boundaries (e.g. `{ min: 7.22, max: 9.55 }`) it also has `locale` as an option.

`min` and `max` are equivalent to 'greater or equal' and 'less or equal', respectively while `gt` and `lt` are their strict counterparts.

`locale` determines the decimal separator and is one of `['ar', 'ar-AE', 'ar-BH', 'ar-DZ', 'ar-EG', 'ar-IQ', 'ar-JO', 'ar-KW', 'ar-LB', 'ar-LY', 'ar-MA', 'ar-QA', 'ar-QM', 'ar-SA', 'ar-SD', 'ar-SY', 'ar-TN', 'ar-YE', 'bg-BG', 'cs-CZ', 'da-DK', 'de-DE', 'en-AU', 'en-GB', 'en-HK', 'en-IN', 'en-NZ', 'en-US', 'en-ZA', 'en-ZM', 'es-ES', 'fr-CA', 'fr-FR', 'hu-HU', 'it-IT', 'nb-NO', 'nl-NL', 'nn-NO', 'pl-PL', 'pt-BR', 'pt-PT', 'ru-RU', 'sl-SI', 'sr-RS', 'sr-RS@latin', 'sv-SE', 'tr-TR', 'uk-UA']`. Locale list is `validator.isFloatLocales`. -**isFQDN(str [, options])** | check if the string is a fully qualified domain name (e.g. domain.com).

`options` is an object which defaults to `{ require_tld: true, allow_underscores: false, allow_trailing_dot: false, allow_numeric_tld: false, allow_wildcard: false, ignore_max_length: false }`. If `allow_wildcard` is set to true, the validator will allow domain starting with `*.` (e.g. `*.example.com` or `*.shop.example.com`). -**isFreightContainerID(str)** | alias for `isISO6346`, check if the string is a valid [ISO 6346](https://en.wikipedia.org/wiki/ISO_6346) shipping container identification. -**isFullWidth(str)** | check if the string contains any full-width chars. -**isHalfWidth(str)** | check if the string contains any half-width chars. -**isHash(str, algorithm)** | check if the string is a hash of type algorithm.

Algorithm is one of `['crc32', 'crc32b', 'md4', 'md5', 'ripemd128', 'ripemd160', 'sha1', 'sha256', 'sha384', 'sha512', 'tiger128', 'tiger160', 'tiger192']`. -**isHexadecimal(str)** | check if the string is a hexadecimal number. -**isHexColor(str)** | check if the string is a hexadecimal color. -**isHSL(str)** | check if the string is an HSL (hue, saturation, lightness, optional alpha) color based on [CSS Colors Level 4 specification][CSS Colors Level 4 Specification].

Comma-separated format supported. Space-separated format supported with the exception of a few edge cases (ex: `hsl(200grad+.1%62%/1)`). -**isIBAN(str, [, options])** | check if the string is an IBAN (International Bank Account Number).

`options` is an object which accepts two attributes: `whitelist`: where you can restrict IBAN codes you want to receive data from and `blacklist`: where you can remove some of the countries from the current list. For both you can use an array with the following values `['AD','AE','AL','AT','AZ','BA','BE','BG','BH','BR','BY','CH','CR','CY','CZ','DE','DK','DO','EE','EG','ES','FI','FO','FR','GB','GE','GI','GL','GR','GT','HR','HU','IE','IL','IQ','IR','IS','IT','JO','KW','KZ','LB','LC','LI','LT','LU','LV','MC','MD','ME','MK','MR','MT','MU','MZ','NL','NO','PK','PL','PS','PT','QA','RO','RS','SA','SC','SE','SI','SK','SM','SV','TL','TN','TR','UA','VA','VG','XK']`. -**isIdentityCard(str [, locale])** | check if the string is a valid identity card code.

`locale` is one of `['LK', 'PL', 'ES', 'FI', 'IN', 'IT', 'IR', 'MZ', 'NO', 'TH', 'zh-TW', 'he-IL', 'ar-LY', 'ar-TN', 'zh-CN', 'zh-HK']` OR `'any'`. If 'any' is used, function will check if any of the locales match.

Defaults to 'any'. -**isIMEI(str [, options]))** | check if the string is a valid [IMEI number][IMEI]. IMEI should be of format `###############` or `##-######-######-#`.

`options` is an object which can contain the keys `allow_hyphens`. Defaults to first format. If `allow_hyphens` is set to true, the validator will validate the second format. -**isIn(str, values)** | check if the string is in an array of allowed values. -**isInt(str [, options])** | check if the string is an integer.

`options` is an object which can contain the keys `min` and/or `max` to check the integer is within boundaries (e.g. `{ min: 10, max: 99 }`). `options` can also contain the key `allow_leading_zeroes`, which when set to false will disallow integer values with leading zeroes (e.g. `{ allow_leading_zeroes: false }`). Finally, `options` can contain the keys `gt` and/or `lt` which will enforce integers being greater than or less than, respectively, the value provided (e.g. `{gt: 1, lt: 4}` for a number between 1 and 4). -**isIP(str [, version])** | check if the string is an IP (version 4 or 6). -**isIPRange(str [, version])** | check if the string is an IP Range (version 4 or 6). -**isISBN(str [, options])** | check if the string is an [ISBN][ISBN].

`options` is an object that has no default.
**Options:**
`version`: ISBN version to compare to. Accepted values are '10' and '13'. If none provided, both will be tested. -**isISIN(str)** | check if the string is an [ISIN][ISIN] (stock/security identifier). -**isISO6346(str)** | check if the string is a valid [ISO 6346](https://en.wikipedia.org/wiki/ISO_6346) shipping container identification. -**isISO6391(str)** | check if the string is a valid [ISO 639-1][ISO 639-1] language code. -**isISO8601(str [, options])** | check if the string is a valid [ISO 8601][ISO 8601] date.
`options` is an object which defaults to `{ strict: false, strictSeparator: false }`. If `strict` is true, date strings with invalid dates like `2009-02-29` will be invalid. If `strictSeparator` is true, date strings with date and time separated by anything other than a T will be invalid. -**isISO31661Alpha2(str)** | check if the string is a valid [ISO 3166-1 alpha-2][ISO 3166-1 alpha-2] officially assigned country code. -**isISO31661Alpha3(str)** | check if the string is a valid [ISO 3166-1 alpha-3][ISO 3166-1 alpha-3] officially assigned country code. -**isISO4217(str)** | check if the string is a valid [ISO 4217][ISO 4217] officially assigned currency code. -**isISRC(str)** | check if the string is an [ISRC][ISRC]. -**isISSN(str [, options])** | check if the string is an [ISSN][ISSN].

`options` is an object which defaults to `{ case_sensitive: false, require_hyphen: false }`. If `case_sensitive` is true, ISSNs with a lowercase `'x'` as the check digit are rejected. -**isJSON(str [, options])** | check if the string is valid JSON (note: uses JSON.parse).

`options` is an object which defaults to `{ allow_primitives: false }`. If `allow_primitives` is true, the primitives 'true', 'false' and 'null' are accepted as valid JSON values. -**isJWT(str)** | check if the string is valid JWT token. -**isLatLong(str [, options])** | check if the string is a valid latitude-longitude coordinate in the format `lat,long` or `lat, long`.

`options` is an object that defaults to `{ checkDMS: false }`. Pass `checkDMS` as `true` to validate DMS(degrees, minutes, and seconds) latitude-longitude format. -**isLength(str [, options])** | check if the string's length falls in a range.

`options` is an object which defaults to `{ min: 0, max: undefined }`. Note: this function takes into account surrogate pairs. -**isLicensePlate(str, locale)** | check if the string matches the format of a country's license plate.

`locale` is one of `['cs-CZ', 'de-DE', 'de-LI', 'en-IN', 'es-AR', 'hu-HU', 'pt-BR', 'pt-PT', 'sq-AL', 'sv-SE']` or `'any'`. -**isLocale(str)** | check if the string is a locale. -**isLowercase(str)** | check if the string is lowercase. -**isLuhnNumber(str)** | check if the string passes the [Luhn algorithm check](https://en.wikipedia.org/wiki/Luhn_algorithm). -**isMACAddress(str [, options])** | check if the string is a MAC address.

`options` is an object which defaults to `{ no_separators: false }`. If `no_separators` is true, the validator will allow MAC addresses without separators. Also, it allows the use of hyphens, spaces or dots e.g. '01 02 03 04 05 ab', '01-02-03-04-05-ab' or '0102.0304.05ab'. The options also allow a `eui` property to specify if it needs to be validated against EUI-48 or EUI-64. The accepted values of `eui` are: 48, 64. -**isMagnetURI(str)** | check if the string is a [Magnet URI format][Magnet URI Format]. -**isMailtoURI(str, [, options])** | check if the string is a [Magnet URI format][Mailto URI Format].

`options` is an object of validating emails inside the URI (check `isEmail`s options for details). -**isMD5(str)** | check if the string is a MD5 hash.

Please note that you can also use the `isHash(str, 'md5')` function. Keep in mind that MD5 has some collision weaknesses compared to other algorithms (e.g., SHA). -**isMimeType(str)** | check if the string matches to a valid [MIME type][MIME Type] format. -**isMobilePhone(str [, locale [, options]])** | check if the string is a mobile phone number,

`locale` is either an array of locales (e.g. `['sk-SK', 'sr-RS']`) OR one of `['am-Am', 'ar-AE', 'ar-BH', 'ar-DZ', 'ar-EG', 'ar-EH', 'ar-IQ', 'ar-JO', 'ar-KW', 'ar-PS', 'ar-SA', 'ar-SD', 'ar-SY', 'ar-TN', 'ar-YE', 'az-AZ', 'az-LB', 'az-LY', 'be-BY', 'bg-BG', 'bn-BD', 'bs-BA', 'ca-AD', 'cs-CZ', 'da-DK', 'de-AT', 'de-CH', 'de-DE', 'de-LU', 'dv-MV', 'dz-BT', 'el-CY', 'el-GR', 'en-AG', 'en-AI', 'en-AU', 'en-BM', 'en-BS', 'en-BW', 'en-CA', 'en-GB', 'en-GG', 'en-GH', 'en-GY', 'en-HK', 'en-IE', 'en-IN', 'en-JM', 'en-KE', 'en-KI', 'en-KN', 'en-LS', 'en-MO', 'en-MT', 'en-MU', 'en-MW', 'en-NG', 'en-NZ', 'en-PG', 'en-PH', 'en-PK', 'en-RW', 'en-SG', 'en-SL', 'en-SS', 'en-TZ', 'en-UG', 'en-US', 'en-ZA', 'en-ZM', 'en-ZW', 'es-AR', 'es-BO', 'es-CL', 'es-CO', 'es-CR', 'es-CU', 'es-DO', 'es-EC', 'es-ES', 'es-HN', 'es-MX', 'es-NI', 'es-PA', 'es-PE', 'es-PY', 'es-SV', 'es-UY', 'es-VE', 'et-EE', 'fa-AF', 'fa-IR', 'fi-FI', 'fj-FJ', 'fo-FO', 'fr-BE', 'fr-BF', 'fr-BJ', 'fr-CD', 'fr-CF', 'fr-FR', 'fr-GF', 'fr-GP', 'fr-MQ', 'fr-PF', 'fr-RE', 'fr-WF', 'ga-IE', 'he-IL', 'hu-HU', 'id-ID', 'ir-IR', 'it-IT', 'it-SM', 'ja-JP', 'ka-GE', 'kk-KZ', 'kl-GL', 'ko-KR', 'ky-KG', 'lt-LT', 'mg-MG', 'mn-MN', 'ms-MY', 'my-MM', 'mz-MZ', 'nb-NO', 'ne-NP', 'nl-AW', 'nl-BE', 'nl-NL', 'nn-NO', 'pl-PL', 'pt-AO', 'pt-BR', 'pt-PT', 'ro-Md', 'ro-RO', 'ru-RU', 'si-LK', 'sk-SK', 'sl-SI', 'so-SO', 'sq-AL', 'sr-RS', 'sv-SE', 'tg-TJ', 'th-TH', 'tk-TM', 'tr-TR', 'uk-UA', 'uz-UZ', 'vi-VN', 'zh-CN', 'zh-HK', 'zh-MO', 'zh-TW']` OR defaults to `'any'`. If 'any' or a falsey value is used, function will check if any of the locales match).

`options` is an optional object that can be supplied with the following keys: `strictMode`, if this is set to `true`, the mobile phone number must be supplied with the country code and therefore must start with `+`. Locale list is `validator.isMobilePhoneLocales`. -**isMongoId(str)** | check if the string is a valid hex-encoded representation of a [MongoDB ObjectId][mongoid]. -**isMultibyte(str)** | check if the string contains one or more multibyte chars. -**isNumeric(str [, options])** | check if the string contains only numbers.

`options` is an object which defaults to `{ no_symbols: false }` it also has `locale` as an option. If `no_symbols` is true, the validator will reject numeric strings that feature a symbol (e.g. `+`, `-`, or `.`).

`locale` determines the decimal separator and is one of `['ar', 'ar-AE', 'ar-BH', 'ar-DZ', 'ar-EG', 'ar-IQ', 'ar-JO', 'ar-KW', 'ar-LB', 'ar-LY', 'ar-MA', 'ar-QA', 'ar-QM', 'ar-SA', 'ar-SD', 'ar-SY', 'ar-TN', 'ar-YE', 'bg-BG', 'cs-CZ', 'da-DK', 'de-DE', 'en-AU', 'en-GB', 'en-HK', 'en-IN', 'en-NZ', 'en-US', 'en-ZA', 'en-ZM', 'es-ES', 'fr-FR', 'fr-CA', 'hu-HU', 'it-IT', 'nb-NO', 'nl-NL', 'nn-NO', 'pl-PL', 'pt-BR', 'pt-PT', 'ru-RU', 'sl-SI', 'sr-RS', 'sr-RS@latin', 'sv-SE', 'tr-TR', 'uk-UA']`. -**isOctal(str)** | check if the string is a valid octal number. -**isPassportNumber(str, countryCode)** | check if the string is a valid passport number.

`countryCode` is one of `['AM', 'AR', 'AT', 'AU', 'AZ', 'BE', 'BG', 'BY', 'BR', 'CA', 'CH', 'CN', 'CY', 'CZ', 'DE', 'DK', 'DZ', 'EE', 'ES', 'FI', 'FR', 'GB', 'GR', 'HR', 'HU', 'IE', 'IN', 'IR', 'ID', 'IS', 'IT', 'JM', 'JP', 'KR', 'KZ', 'LI', 'LT', 'LU', 'LV', 'LY', 'MT', 'MX', 'MY', 'MZ', 'NL', 'NZ', 'PH', 'PK', 'PL', 'PT', 'RO', 'RU', 'SE', 'SL', 'SK', 'TH', 'TR', 'UA', 'US', 'ZA']`. -**isPort(str)** | check if the string is a valid port number. -**isPostalCode(str, locale)** | check if the string is a postal code.

`locale` is one of `['AD', 'AT', 'AU', 'AZ', 'BA', 'BE', 'BG', 'BR', 'BY', 'CA', 'CH', 'CN', 'CZ', 'DE', 'DK', 'DO', 'DZ', 'EE', 'ES', 'FI', 'FR', 'GB', 'GR', 'HR', 'HT', 'HU', 'ID', 'IE', 'IL', 'IN', 'IR', 'IS', 'IT', 'JP', 'KE', 'KR', 'LI', 'LK', 'LT', 'LU', 'LV', 'MG', 'MT', 'MX', 'MY', 'NL', 'NO', 'NP', 'NZ', 'PL', 'PR', 'PT', 'RO', 'RU', 'SA', 'SE', 'SG', 'SI', 'SK', 'TH', 'TN', 'TW', 'UA', 'US', 'ZA', 'ZM']` OR `'any'`. If 'any' is used, function will check if any of the locales match. Locale list is `validator.isPostalCodeLocales`. -**isRFC3339(str)** | check if the string is a valid [RFC 3339][RFC 3339] date. -**isRgbColor(str [, includePercentValues])** | check if the string is a rgb or rgba color.

`includePercentValues` defaults to `true`. If you don't want to allow to set `rgb` or `rgba` values with percents, like `rgb(5%,5%,5%)`, or `rgba(90%,90%,90%,.3)`, then set it to false. -**isSemVer(str)** | check if the string is a Semantic Versioning Specification (SemVer). -**isSurrogatePair(str)** | check if the string contains any surrogate pairs chars. -**isUppercase(str)** | check if the string is uppercase. -**isSlug(str)** | check if the string is of type slug. -**isStrongPassword(str [, options])** | check if the string can be considered a strong password or not. Allows for custom requirements or scoring rules. If `returnScore` is true, then the function returns an integer score for the password rather than a boolean.
Default options:
`{ minLength: 8, minLowercase: 1, minUppercase: 1, minNumbers: 1, minSymbols: 1, returnScore: false, pointsPerUnique: 1, pointsPerRepeat: 0.5, pointsForContainingLower: 10, pointsForContainingUpper: 10, pointsForContainingNumber: 10, pointsForContainingSymbol: 10 }` -**isTime(str [, options])** | check if the string is a valid time e.g. [`23:01:59`, new Date().toLocaleTimeString()].

`options` is an object which can contain the keys `hourFormat` or `mode`.

`hourFormat` is a key and defaults to `'hour24'`.

`mode` is a key and defaults to `'default'`.

`hourFomat` can contain the values `'hour12'` or `'hour24'`, `'hour24'` will validate hours in 24 format and `'hour12'` will validate hours in 12 format.

`mode` can contain the values `'default'` or `'withSeconds'`, `'default'` will validate `HH:MM` format, `'withSeconds'` will validate the `HH:MM:SS` format. -**isTaxID(str, locale)** | check if the string is a valid Tax Identification Number. Default locale is `en-US`.

More info about exact TIN support can be found in `src/lib/isTaxID.js`.

Supported locales: `[ 'bg-BG', 'cs-CZ', 'de-AT', 'de-DE', 'dk-DK', 'el-CY', 'el-GR', 'en-CA', 'en-GB', 'en-IE', 'en-US', 'es-AR', 'es-ES', 'et-EE', 'fi-FI', 'fr-BE', 'fr-CA', 'fr-FR', 'fr-LU', 'hr-HR', 'hu-HU', 'it-IT', 'lb-LU', 'lt-LT', 'lv-LV', 'mt-MT', 'nl-BE', 'nl-NL', 'pl-PL', 'pt-BR', 'pt-PT', 'ro-RO', 'sk-SK', 'sl-SI', 'sv-SE' ]`. -**isURL(str [, options])** | check if the string is a URL.

`options` is an object which defaults to `{ protocols: ['http','https','ftp'], require_tld: true, require_protocol: false, require_host: true, require_port: false, require_valid_protocol: true, allow_underscores: false, host_whitelist: false, host_blacklist: false, allow_trailing_dot: false, allow_protocol_relative_urls: false, allow_fragments: true, allow_query_components: true, disallow_auth: false, validate_length: true }`.

`require_protocol` - if set to true isURL will return false if protocol is not present in the URL.
`require_valid_protocol` - isURL will check if the URL's protocol is present in the protocols option.
`protocols` - valid protocols can be modified with this option.
`require_host` - if set to false isURL will not check if host is present in the URL.
`require_port` - if set to true isURL will check if port is present in the URL.
`allow_protocol_relative_urls` - if set to true protocol relative URLs will be allowed.
`allow_fragments` - if set to false isURL will return false if fragments are present.
`allow_query_components` - if set to false isURL will return false if query components are present.
`validate_length` - if set to false isURL will skip string length validation (2083 characters is IE max URL length). -**isUUID(str [, version])** | check if the string is a UUID (version 1, 2, 3, 4 or 5). -**isVariableWidth(str)** | check if the string contains a mixture of full and half-width chars. -**isVAT(str, countryCode)** | check if the string is a [valid VAT number][VAT Number] if validation is available for the given country code matching [ISO 3166-1 alpha-2][ISO 3166-1 alpha-2].

`countryCode` is one of `['AL', 'AR', 'AT', 'AU', 'BE', 'BG', 'BO', 'BR', 'BY', 'CA', 'CH', 'CL', 'CO', 'CR', 'CY', 'CZ', 'DE', 'DK', 'DO', 'EC', 'EE', 'EL', 'ES', 'FI', 'FR', 'GB', 'GT', 'HN', 'HR', 'HU', 'ID', 'IE', 'IL', 'IN', 'IS', 'IT', 'KZ', 'LT', 'LU', 'LV', 'MK', 'MT', 'MX', 'NG', 'NI', 'NL', 'NO', 'NZ', 'PA', 'PE', 'PH', 'PL', 'PT', 'PY', 'RO', 'RS', 'RU', 'SA', 'SE', 'SI', 'SK', 'SM', 'SV', 'TR', 'UA', 'UY', 'UZ', 'VE']`. -**isWhitelisted(str, chars)** | check if the string consists only of characters that appear in the whitelist `chars`. -**matches(str, pattern [, modifiers])** | check if the string matches the pattern.

Either `matches('foo', /foo/i)` or `matches('foo', 'foo', 'i')`. +| Validator | Description | +| --------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| **contains(str, seed [, options])** | check if the string contains the seed.

`options` is an object that defaults to `{ ignoreCase: false, minOccurrences: 1 }`.
Options:
`ignoreCase`: Ignore case when doing comparison, default false.
`minOccurrences`: Minimum number of occurrences for the seed in the string. Defaults to 1. | +| **equals(str, comparison)** | check if the string matches the comparison. | +| **isAbaRouting(str)** | check if the string is an ABA routing number for US bank account / cheque. | +| **isAfter(str [, options])** | check if the string is a date that is after the specified date.

`options` is an object that defaults to `{ comparisonDate: Date().toString() }`.
**Options:**
`comparisonDate`: Date to compare to. Defaults to `Date().toString()` (now). | +| **isAlpha(str [, locale, options])** | check if the string contains only letters (a-zA-Z).

`locale` is one of `['ar', 'ar-AE', 'ar-BH', 'ar-DZ', 'ar-EG', 'ar-IQ', 'ar-JO', 'ar-KW', 'ar-LB', 'ar-LY', 'ar-MA', 'ar-QA', 'ar-QM', 'ar-SA', 'ar-SD', 'ar-SY', 'ar-TN', 'ar-YE', 'bg-BG', 'bn', 'cs-CZ', 'da-DK', 'de-DE', 'el-GR', 'en-AU', 'en-GB', 'en-HK', 'en-IN', 'en-NZ', 'en-US', 'en-ZA', 'en-ZM', 'eo', 'es-ES', 'fa-IR', 'fi-FI', 'fr-CA', 'fr-FR', 'ga-IE','he', 'hi-IN', 'hu-HU', 'it-IT', 'kk-KZ', 'ko-KR', 'ja-JP', 'ku-IQ', 'nb-NO', 'nl-NL', 'nn-NO', 'pl-PL', 'pt-BR', 'pt-PT', 'ru-RU', 'si-LK', 'sl-SI', 'sk-SK', 'sr-RS', 'sr-RS@latin', 'sv-SE', 'th-TH', 'tr-TR', 'uk-UA']` and defaults to `en-US`. Locale list is `validator.isAlphaLocales`. `options` is an optional object that can be supplied with the following key(s): `ignore` which can either be a String or RegExp of characters to be ignored e.g. " -" will ignore spaces and -'s. | +| **isAlphanumeric(str [, locale, options])** | check if the string contains only letters and numbers (a-zA-Z0-9).

`locale` is one of `['ar', 'ar-AE', 'ar-BH', 'ar-DZ', 'ar-EG', 'ar-IQ', 'ar-JO', 'ar-KW', 'ar-LB', 'ar-LY', 'ar-MA', 'ar-QA', 'ar-QM', 'ar-SA', 'ar-SD', 'ar-SY', 'ar-TN', 'ar-YE', 'bn', 'bg-BG', 'cs-CZ', 'da-DK', 'de-DE', 'el-GR', 'en-AU', 'en-GB', 'en-HK', 'en-IN', 'en-NZ', 'en-US', 'en-ZA', 'en-ZM', 'eo', 'es-ES', 'fa-IR', 'fi-FI', 'fr-CA', 'fr-FR', 'ga-IE', 'he', 'hi-IN', 'hu-HU', 'it-IT', 'kk-KZ', 'ko-KR', 'ja-JP','ku-IQ', 'nb-NO', 'nl-NL', 'nn-NO', 'pl-PL', 'pt-BR', 'pt-PT', 'ru-RU', 'si-LK', 'sl-SI', 'sk-SK', 'sr-RS', 'sr-RS@latin', 'sv-SE', 'th-TH', 'tr-TR', 'uk-UA']`) and defaults to `en-US`. Locale list is `validator.isAlphanumericLocales`. `options` is an optional object that can be supplied with the following key(s): `ignore` which can either be a String or RegExp of characters to be ignored e.g. " -" will ignore spaces and -'s. | +| **isAscii(str)** | check if the string contains ASCII chars only. | +| **isBase32(str [, options])** | check if the string is base32 encoded. `options` is optional and defaults to `{ crockford: false }`.
When `crockford` is true it tests the given base32 encoded string using [Crockford's base32 alternative][Crockford Base32]. | +| **isBase58(str)** | check if the string is base58 encoded. | +| **isBase64(str [, options])** | check if the string is base64 encoded. `options` is optional and defaults to `{ urlSafe: false, padding: true }`
when `urlSafe` is true default value for `padding` is false and it tests the given base64 encoded string is [url safe][Base64 URL Safe]. | +| **isBefore(str [, options])** | check if the string is a date that is before the specified date.

`options` is an object that defaults to `{ comparisonDate: Date().toString() }`.

**Options:**
`comparisonDate`: Date to compare to. Defaults to `Date().toString()` (now). | +| **isBIC(str)** | check if the string is a BIC (Bank Identification Code) or SWIFT code. | +| **isBoolean(str [, options])** | check if the string is a boolean.
`options` is an object which defaults to `{ loose: false }`. If `loose` is set to false, the validator will strictly match ['true', 'false', '0', '1']. If `loose` is set to true, the validator will also match 'yes', 'no', and will match a valid boolean string of any case. (e.g.: ['true', 'True', 'TRUE']). | +| **isBtcAddress(str)** | check if the string is a valid BTC address. | +| **isByteLength(str [, options])** | check if the string's length (in UTF-8 bytes) falls in a range.

`options` is an object which defaults to `{ min: 0, max: undefined }`. | +| **isCreditCard(str [, options])** | check if the string is a credit card number.

`options` is an optional object that can be supplied with the following key(s): `provider` is an optional key whose value should be a string, and defines the company issuing the credit card. Valid values include `['amex', 'dinersclub', 'discover', 'jcb', 'mastercard', 'unionpay', 'visa']` or blank will check for any provider. | +| **isCurrency(str [, options])** | check if the string is a valid currency amount.

`options` is an object which defaults to `{ symbol: '$', require_symbol: false, allow_space_after_symbol: false, symbol_after_digits: false, allow_negatives: true, parens_for_negatives: false, negative_sign_before_digits: false, negative_sign_after_digits: false, allow_negative_sign_placeholder: false, thousands_separator: ',', decimal_separator: '.', allow_decimal: true, require_decimal: false, digits_after_decimal: [2], allow_space_after_digits: false }`.
**Note:** The array `digits_after_decimal` is filled with the exact number of digits allowed not a range, for example a range 1 to 3 will be given as [1, 2, 3]. | +| **isDataURI(str)** | check if the string is a [data uri format][Data URI Format]. | +| **isDate(str [, options])** | check if the string is a valid date. e.g. [`2002-07-15`, new Date()].

`options` is an object which can contain the keys `format`, `strictMode` and/or `delimiters`.

`format` is a string and defaults to `YYYY/MM/DD`.

`strictMode` is a boolean and defaults to `false`. If `strictMode` is set to true, the validator will reject strings different from `format`.

`delimiters` is an array of allowed date delimiters and defaults to `['/', '-']`. | +| **isDecimal(str [, options])** | check if the string represents a decimal number, such as 0.1, .3, 1.1, 1.00003, 4.0, etc.

`options` is an object which defaults to `{force_decimal: false, decimal_digits: '1,', locale: 'en-US'}`.

`locale` determines the decimal separator and is one of `['ar', 'ar-AE', 'ar-BH', 'ar-DZ', 'ar-EG', 'ar-IQ', 'ar-JO', 'ar-KW', 'ar-LB', 'ar-LY', 'ar-MA', 'ar-QA', 'ar-QM', 'ar-SA', 'ar-SD', 'ar-SY', 'ar-TN', 'ar-YE', 'bg-BG', 'cs-CZ', 'da-DK', 'de-DE', 'el-GR', 'en-AU', 'en-GB', 'en-HK', 'en-IN', 'en-NZ', 'en-US', 'en-ZA', 'en-ZM', 'eo', 'es-ES', 'fa', 'fa-AF', 'fa-IR', 'fr-FR', 'fr-CA', 'hu-HU', 'id-ID', 'it-IT', 'ku-IQ', 'nb-NO', 'nl-NL', 'nn-NO', 'pl-PL', 'pl-Pl', 'pt-BR', 'pt-PT', 'ru-RU', 'sl-SI', 'sr-RS', 'sr-RS@latin', 'sv-SE', 'tr-TR', 'uk-UA', 'vi-VN']`.
**Note:** `decimal_digits` is given as a range like '1,3', a specific value like '3' or min like '1,'. | +| **isDivisibleBy(str, number)** | check if the string is a number that is divisible by another. | +| **isEAN(str)** | check if the string is an [EAN (European Article Number)][European Article Number]. | +| **isEmail(str [, options])** | check if the string is an email.

`options` is an object which defaults to `{ allow_display_name: false, require_display_name: false, allow_utf8_local_part: true, require_tld: true, allow_ip_domain: false, allow_underscores: false, domain_specific_validation: false, blacklisted_chars: '', host_blacklist: [] }`. If `allow_display_name` is set to true, the validator will also match `Display Name `. If `require_display_name` is set to true, the validator will reject strings without the format `Display Name `. If `allow_utf8_local_part` is set to false, the validator will not allow any non-English UTF8 character in email address' local part. If `require_tld` is set to false, email addresses without a TLD in their domain will also be matched. If `ignore_max_length` is set to true, the validator will not check for the standard max length of an email. If `allow_ip_domain` is set to true, the validator will allow IP addresses in the host part. If `domain_specific_validation` is true, some additional validation will be enabled, e.g. disallowing certain syntactically valid email addresses that are rejected by Gmail. If `blacklisted_chars` receives a string, then the validator will reject emails that include any of the characters in the string, in the name part. If `host_blacklist` is set to an array of strings or regexp, and the part of the email after the `@` symbol matches one of the strings defined in it, the validation fails. If `host_whitelist` is set to an array of strings or regexp, and the part of the email after the `@` symbol matches none of the strings defined in it, the validation fails. | +| **isEmpty(str [, options])** | check if the string has a length of zero.

`options` is an object which defaults to `{ ignore_whitespace: false }`. | +| **isEthereumAddress(str)** | check if the string is an [Ethereum][Ethereum] address. Does not validate address checksums. | +| **isFloat(str [, options])** | check if the string is a float.

`options` is an object which can contain the keys `min`, `max`, `gt`, and/or `lt` to validate the float is within boundaries (e.g. `{ min: 7.22, max: 9.55 }`) it also has `locale` as an option.

`min` and `max` are equivalent to 'greater or equal' and 'less or equal', respectively while `gt` and `lt` are their strict counterparts.

`locale` determines the decimal separator and is one of `['ar', 'ar-AE', 'ar-BH', 'ar-DZ', 'ar-EG', 'ar-IQ', 'ar-JO', 'ar-KW', 'ar-LB', 'ar-LY', 'ar-MA', 'ar-QA', 'ar-QM', 'ar-SA', 'ar-SD', 'ar-SY', 'ar-TN', 'ar-YE', 'bg-BG', 'cs-CZ', 'da-DK', 'de-DE', 'en-AU', 'en-GB', 'en-HK', 'en-IN', 'en-NZ', 'en-US', 'en-ZA', 'en-ZM', 'eo', 'es-ES', 'fr-CA', 'fr-FR', 'hu-HU', 'it-IT', 'nb-NO', 'nl-NL', 'nn-NO', 'pl-PL', 'pt-BR', 'pt-PT', 'ru-RU', 'sl-SI', 'sr-RS', 'sr-RS@latin', 'sv-SE', 'tr-TR', 'uk-UA']`. Locale list is `validator.isFloatLocales`. | +| **isFQDN(str [, options])** | check if the string is a fully qualified domain name (e.g. domain.com).

`options` is an object which defaults to `{ require_tld: true, allow_underscores: false, allow_trailing_dot: false, allow_numeric_tld: false, allow_wildcard: false, ignore_max_length: false }`. If `allow_wildcard` is set to true, the validator will allow domain starting with `*.` (e.g. `*.example.com` or `*.shop.example.com`). | +| **isFreightContainerID(str)** | alias for `isISO6346`, check if the string is a valid [ISO 6346](https://en.wikipedia.org/wiki/ISO_6346) shipping container identification. | +| **isFullWidth(str)** | check if the string contains any full-width chars. | +| **isHalfWidth(str)** | check if the string contains any half-width chars. | +| **isHash(str, algorithm)** | check if the string is a hash of type algorithm.

Algorithm is one of `['crc32', 'crc32b', 'md4', 'md5', 'ripemd128', 'ripemd160', 'sha1', 'sha256', 'sha384', 'sha512', 'tiger128', 'tiger160', 'tiger192']`. | +| **isHexadecimal(str)** | check if the string is a hexadecimal number. | +| **isHexColor(str)** | check if the string is a hexadecimal color. | +| **isHSL(str)** | check if the string is an HSL (hue, saturation, lightness, optional alpha) color based on [CSS Colors Level 4 specification][CSS Colors Level 4 Specification].

Comma-separated format supported. Space-separated format supported with the exception of a few edge cases (ex: `hsl(200grad+.1%62%/1)`). | +| **isIBAN(str, [, options])** | check if the string is an IBAN (International Bank Account Number).

`options` is an object which accepts two attributes: `whitelist`: where you can restrict IBAN codes you want to receive data from and `blacklist`: where you can remove some of the countries from the current list. For both you can use an array with the following values `['AD','AE','AL','AT','AZ','BA','BE','BG','BH','BR','BY','CH','CR','CY','CZ','DE','DK','DO','EE','EG','ES','FI','FO','FR','GB','GE','GI','GL','GR','GT','HR','HU','IE','IL','IQ','IR','IS','IT','JO','KW','KZ','LB','LC','LI','LT','LU','LV','MC','MD','ME','MK','MR','MT','MU','MZ','NL','NO','PK','PL','PS','PT','QA','RO','RS','SA','SC','SE','SI','SK','SM','SV','TL','TN','TR','UA','VA','VG','XK']`. | +| **isIdentityCard(str [, locale])** | check if the string is a valid identity card code.

`locale` is one of `['LK', 'PL', 'ES', 'FI', 'IN', 'IT', 'IR', 'MZ', 'NO', 'TH', 'zh-TW', 'he-IL', 'ar-LY', 'ar-TN', 'zh-CN', 'zh-HK', 'PK']` OR `'any'`. If 'any' is used, function will check if any of the locales match.

Defaults to 'any'. | +| **isIMEI(str [, options]))** | check if the string is a valid [IMEI number][IMEI]. IMEI should be of format `###############` or `##-######-######-#`.

`options` is an object which can contain the keys `allow_hyphens`. Defaults to first format. If `allow_hyphens` is set to true, the validator will validate the second format. | +| **isIn(str, values)** | check if the string is in an array of allowed values. | +| **isInt(str [, options])** | check if the string is an integer.

`options` is an object which can contain the keys `min` and/or `max` to check the integer is within boundaries (e.g. `{ min: 10, max: 99 }`). `options` can also contain the key `allow_leading_zeroes`, which when set to false will disallow integer values with leading zeroes (e.g. `{ allow_leading_zeroes: false }`). Finally, `options` can contain the keys `gt` and/or `lt` which will enforce integers being greater than or less than, respectively, the value provided (e.g. `{gt: 1, lt: 4}` for a number between 1 and 4). | +| **isIP(str [, options])** | check if the string is an IP address (version 4 or 6).

`options` is an object that defaults to `{ version: '' }`.

**Options:**
`version`: defines which IP version to compare to. Accepted values: `4`, `6`, `'4'`, `'6'`. | +| **isIPRange(str [, version])** | check if the string is an IP Range (version 4 or 6). | +| **isISBN(str [, options])** | check if the string is an [ISBN][ISBN].

`options` is an object that has no default.
**Options:**
`version`: ISBN version to compare to. Accepted values are '10' and '13'. If none provided, both will be tested. | +| **isISIN(str)** | check if the string is an [ISIN][ISIN] (stock/security identifier). | +| **isISO6346(str)** | check if the string is a valid [ISO 6346](https://en.wikipedia.org/wiki/ISO_6346) shipping container identification. | +| **isISO6391(str)** | check if the string is a valid [ISO 639-1][ISO 639-1] language code. | +| **isISO8601(str [, options])** | check if the string is a valid [ISO 8601][ISO 8601] date.
`options` is an object which defaults to `{ strict: false, strictSeparator: false }`. If `strict` is true, date strings with invalid dates like `2009-02-29` will be invalid. If `strictSeparator` is true, date strings with date and time separated by anything other than a T will be invalid. | +| **isISO15924(str)** | check if the string is a valid [ISO 15924][ISO 15924] officially assigned script code. | +| **isISO31661Alpha2(str)** | check if the string is a valid [ISO 3166-1 alpha-2][ISO 3166-1 alpha-2] officially assigned country code. | +| **isISO31661Alpha3(str)** | check if the string is a valid [ISO 3166-1 alpha-3][ISO 3166-1 alpha-3] officially assigned country code. | +| **isISO31661Numeric(str)** | check if the string is a valid [ISO 3166-1 numeric][ISO 3166-1 numeric] officially assigned country code. | +| **isISO4217(str)** | check if the string is a valid [ISO 4217][ISO 4217] officially assigned currency code. | +| **isISRC(str)** | check if the string is an [ISRC][ISRC]. | +| **isISSN(str [, options])** | check if the string is an [ISSN][ISSN].

`options` is an object which defaults to `{ case_sensitive: false, require_hyphen: false }`. If `case_sensitive` is true, ISSNs with a lowercase `'x'` as the check digit are rejected. | +| **isJSON(str [, options])** | check if the string is valid JSON (note: uses JSON.parse).

`options` is an object which defaults to `{ allow_primitives: false }`. If `allow_primitives` is true, the primitives 'true', 'false' and 'null' are accepted as valid JSON values. | +| **isJWT(str)** | check if the string is valid JWT token. | +| **isLatLong(str [, options])** | check if the string is a valid latitude-longitude coordinate in the format `lat,long` or `lat, long`.

`options` is an object that defaults to `{ checkDMS: false }`. Pass `checkDMS` as `true` to validate DMS(degrees, minutes, and seconds) latitude-longitude format. | +| **isLength(str [, options])** | check if the string's length falls in a range and equal to any of the integers of the `discreteLengths` array if provided.

`options` is an object which defaults to `{ min: 0, max: undefined, discreteLengths: undefined }`. Note: this function takes into account surrogate pairs. | +| **isLicensePlate(str, locale)** | check if the string matches the format of a country's license plate.

`locale` is one of `['cs-CZ', 'de-DE', 'de-LI', 'en-IN', 'en-SG', 'en-PK', 'es-AR', 'hu-HU', 'pt-BR', 'pt-PT', 'sq-AL', 'sv-SE']` or `'any'`. | +| **isLocale(str)** | check if the string is a locale. | +| **isLowercase(str)** | check if the string is lowercase. | +| **isLuhnNumber(str)** | check if the string passes the [Luhn algorithm check](https://en.wikipedia.org/wiki/Luhn_algorithm). | +| **isMACAddress(str [, options])** | check if the string is a MAC address.

`options` is an object which defaults to `{ no_separators: false }`. If `no_separators` is true, the validator will allow MAC addresses without separators. Also, it allows the use of hyphens, spaces or dots e.g. '01 02 03 04 05 ab', '01-02-03-04-05-ab' or '0102.0304.05ab'. The options also allow a `eui` property to specify if it needs to be validated against EUI-48 or EUI-64. The accepted values of `eui` are: 48, 64. | +| **isMagnetURI(str)** | check if the string is a [Magnet URI format][Magnet URI Format]. | +| **isMailtoURI(str, [, options])** | check if the string is a [Mailto URI format][Mailto URI Format].

`options` is an object of validating emails inside the URI (check `isEmail`s options for details). | +| **isMD5(str)** | check if the string is a MD5 hash.

Please note that you can also use the `isHash(str, 'md5')` function. Keep in mind that MD5 has some collision weaknesses compared to other algorithms (e.g., SHA). | +| **isMimeType(str)** | check if the string matches to a valid [MIME type][MIME Type] format. | +| **isMobilePhone(str [, locale [, options]])** | check if the string is a mobile phone number,

`locale` is either an array of locales (e.g. `['sk-SK', 'sr-RS']`) OR one of `['am-Am', 'ar-AE', 'ar-BH', 'ar-DZ', 'ar-EG', 'ar-EH', 'ar-IQ', 'ar-JO', 'ar-KW', 'ar-PS', 'ar-SA', 'ar-SD', 'ar-SY', 'ar-TN', 'ar-YE', 'az-AZ', 'az-LB', 'az-LY', 'be-BY', 'bg-BG', 'bn-BD', 'bs-BA', 'ca-AD', 'cs-CZ', 'da-DK', 'de-AT', 'de-CH', 'de-DE', 'de-LU', 'dv-MV', 'dz-BT', 'el-CY', 'el-GR', 'en-AG', 'en-AI', 'en-AU', 'en-BM', 'en-BS', 'en-BW', 'en-CA', 'en-GB', 'en-GG', 'en-GH', 'en-GY', 'en-HK', 'en-IE', 'en-IN', 'en-JM', 'en-KE', 'en-KI', 'en-KN', 'en-LS', 'en-MO', 'en-MT', 'en-MU', 'en-MW', 'en-NG', 'en-NZ', 'en-PG', 'en-PH', 'en-PK', 'en-RW', 'en-SG', 'en-SL', 'en-SS', 'en-TZ', 'en-UG', 'en-US', 'en-ZA', 'en-ZM', 'en-ZW', 'es-AR', 'es-BO', 'es-CL', 'es-CO', 'es-CR', 'es-CU', 'es-DO', 'es-EC', 'es-ES', 'es-GT','es-HN', 'es-MX', 'es-NI', 'es-PA', 'es-PE', 'es-PY', 'es-SV', 'es-UY', 'es-VE', 'et-EE', 'fa-AF', 'fa-IR', 'fi-FI', 'fj-FJ', 'fo-FO', 'fr-BE', 'fr-BF', 'fr-BJ', 'fr-CD', 'fr-CF', 'fr-FR', 'fr-GF', 'fr-GP', 'fr-MQ', 'fr-PF', 'fr-RE', 'fr-WF', 'ga-IE', 'he-IL', 'hu-HU', 'id-ID', 'ir-IR', 'it-IT', 'it-SM', 'ja-JP', 'ka-GE', 'kk-KZ', 'kl-GL', 'ko-KR', 'ky-KG', 'lt-LT', 'mg-MG', 'mn-MN', 'mk-MK', 'ms-MY', 'my-MM', 'mz-MZ', 'nb-NO', 'ne-NP', 'nl-AW', 'nl-BE', 'nl-NL', 'nn-NO', 'pl-PL', 'pt-AO', 'pt-BR', 'pt-PT', 'ro-Md', 'ro-RO', 'ru-RU', 'si-LK', 'sk-SK', 'sl-SI', 'so-SO', 'sq-AL', 'sr-RS', 'sv-SE', 'tg-TJ', 'th-TH', 'tk-TM', 'tr-TR', 'uk-UA', 'uz-UZ', 'vi-VN', 'zh-CN', 'zh-HK', 'zh-MO', 'zh-TW']` OR defaults to `'any'`. If 'any' or a falsey value is used, function will check if any of the locales match).

`options` is an optional object that can be supplied with the following keys: `strictMode`, if this is set to `true`, the mobile phone number must be supplied with the country code and therefore must start with `+`. Locale list is `validator.isMobilePhoneLocales`. | +| **isMongoId(str)** | check if the string is a valid hex-encoded representation of a [MongoDB ObjectId][mongoid]. | +| **isMultibyte(str)** | check if the string contains one or more multibyte chars. | +| **isNumeric(str [, options])** | check if the string contains only numbers.

`options` is an object which defaults to `{ no_symbols: false }` it also has `locale` as an option. If `no_symbols` is true, the validator will reject numeric strings that feature a symbol (e.g. `+`, `-`, or `.`).

`locale` determines the decimal separator and is one of `['ar', 'ar-AE', 'ar-BH', 'ar-DZ', 'ar-EG', 'ar-IQ', 'ar-JO', 'ar-KW', 'ar-LB', 'ar-LY', 'ar-MA', 'ar-QA', 'ar-QM', 'ar-SA', 'ar-SD', 'ar-SY', 'ar-TN', 'ar-YE', 'bg-BG', 'cs-CZ', 'da-DK', 'de-DE', 'en-AU', 'en-GB', 'en-HK', 'en-IN', 'en-NZ', 'en-US', 'en-ZA', 'en-ZM', 'eo', 'es-ES', 'fr-FR', 'fr-CA', 'hu-HU', 'it-IT', 'nb-NO', 'nl-NL', 'nn-NO', 'pl-PL', 'pt-BR', 'pt-PT', 'ru-RU', 'sl-SI', 'sr-RS', 'sr-RS@latin', 'sv-SE', 'tr-TR', 'uk-UA']`. | +| **isOctal(str)** | check if the string is a valid octal number. | +| **isPassportNumber(str, countryCode)** | check if the string is a valid passport number.

`countryCode` is one of `['AM', 'AR', 'AT', 'AU', 'AZ', 'BE', 'BG', 'BY', 'BR', 'CA', 'CH', 'CN', 'CY', 'CZ', 'DE', 'DK', 'DZ', 'EE', 'ES', 'FI', 'FR', 'GB', 'GR', 'HR', 'HU', 'IE', 'IN', 'IR', 'ID', 'IS', 'IT', 'JM', 'JP', 'KR', 'KZ', 'LI', 'LT', 'LU', 'LV', 'LY', 'MT', 'MX', 'MY', 'MZ', 'NL', 'NZ', 'PH', 'PK', 'PL', 'PT', 'RO', 'RU', 'SE', 'SL', 'SK', 'TH', 'TR', 'UA', 'US', 'ZA']`. Locale list is `validator.passportNumberLocales`. | +| **isPort(str)** | check if the string is a valid port number. | +| **isPostalCode(str, locale)** | check if the string is a postal code.

`locale` is one of `['AD', 'AT', 'AU', 'AZ', 'BA', 'BE', 'BG', 'BR', 'BY', 'CA', 'CH', 'CN', 'CO', 'CZ', 'DE', 'DK', 'DO', 'DZ', 'EE', 'ES', 'FI', 'FR', 'GB', 'GR', 'HR', 'HT', 'HU', 'ID', 'IE', 'IL', 'IN', 'IR', 'IS', 'IT', 'JP', 'KE', 'KR', 'LI', 'LK', 'LT', 'LU', 'LV', 'MG', 'MT', 'MX', 'MY', 'NL', 'NO', 'NP', 'NZ', 'PL', 'PR', 'PT', 'RO', 'RU', 'SA', 'SE', 'SG', 'SI', 'SK', 'TH', 'TN', 'TW', 'UA', 'US', 'ZA', 'ZM']` OR `'any'`. If 'any' is used, function will check if any of the locales match. Locale list is `validator.isPostalCodeLocales`. | +| **isRFC3339(str)** | check if the string is a valid [RFC 3339][RFC 3339] date. | +| **isRgbColor(str [,options])** | check if the string is a rgb or rgba color.

`options` is an object with the following properties

`includePercentValues` defaults to `true`. If you don't want to allow to set `rgb` or `rgba` values with percents, like `rgb(5%,5%,5%)`, or `rgba(90%,90%,90%,.3)`, then set it to false.

`allowSpaces` defaults to `true`, which prohibits whitespace. If set to false, whitespace between color values is allowed, such as `rgb(255, 255, 255)` or even `rgba(255, 128, 0, 0.7)`. | +| **isSemVer(str)** | check if the string is a Semantic Versioning Specification (SemVer). | +| **isSurrogatePair(str)** | check if the string contains any surrogate pairs chars. | +| **isUppercase(str)** | check if the string is uppercase. | +| **isSlug(str)** | check if the string is of type slug. | +| **isStrongPassword(str [, options])** | check if the string can be considered a strong password or not. Allows for custom requirements or scoring rules. If `returnScore` is true, then the function returns an integer score for the password rather than a boolean.
Default options:
`{ minLength: 8, minLowercase: 1, minUppercase: 1, minNumbers: 1, minSymbols: 1, returnScore: false, pointsPerUnique: 1, pointsPerRepeat: 0.5, pointsForContainingLower: 10, pointsForContainingUpper: 10, pointsForContainingNumber: 10, pointsForContainingSymbol: 10 }` | +| **isTime(str [, options])** | check if the string is a valid time e.g. [`23:01:59`, new Date().toLocaleTimeString()].

`options` is an object which can contain the keys `hourFormat` or `mode`.

`hourFormat` is a key and defaults to `'hour24'`.

`mode` is a key and defaults to `'default'`.

`hourFormat` can contain the values `'hour12'` or `'hour24'`, `'hour24'` will validate hours in 24 format and `'hour12'` will validate hours in 12 format.

`mode` can contain the values `'default', 'withSeconds', withOptionalSeconds`, `'default'` will validate `HH:MM` format, `'withSeconds'` will validate the `HH:MM:SS` format, `'withOptionalSeconds'` will validate `'HH:MM'` and `'HH:MM:SS'` formats. | +| **isTaxID(str, locale)** | check if the string is a valid Tax Identification Number. Default locale is `en-US`.

More info about exact TIN support can be found in `src/lib/isTaxID.js`.

Supported locales: `[ 'bg-BG', 'cs-CZ', 'de-AT', 'de-DE', 'dk-DK', 'el-CY', 'el-GR', 'en-CA', 'en-GB', 'en-IE', 'en-US', 'es-AR', 'es-ES', 'et-EE', 'fi-FI', 'fr-BE', 'fr-CA', 'fr-FR', 'fr-LU', 'hr-HR', 'hu-HU', 'it-IT', 'lb-LU', 'lt-LT', 'lv-LV', 'mt-MT', 'nl-BE', 'nl-NL', 'pl-PL', 'pt-BR', 'pt-PT', 'ro-RO', 'sk-SK', 'sl-SI', 'sv-SE', 'uk-UA']`. | +| **isURL(str [, options])** | check if the string is a URL.

`options` is an object which defaults to `{ protocols: ['http','https','ftp'], require_tld: true, require_protocol: false, require_host: true, require_port: false, require_valid_protocol: true, allow_underscores: false, host_whitelist: false, host_blacklist: false, allow_trailing_dot: false, allow_protocol_relative_urls: false, allow_fragments: true, allow_query_components: true, disallow_auth: false, validate_length: true }`.

`require_protocol` - if set to true isURL will return false if protocol is not present in the URL.
`require_valid_protocol` - isURL will check if the URL's protocol is present in the protocols option.
`protocols` - valid protocols can be modified with this option.
`require_host` - if set to false isURL will not check if host is present in the URL.
`require_port` - if set to true isURL will check if port is present in the URL.
`allow_protocol_relative_urls` - if set to true protocol relative URLs will be allowed.
`allow_fragments` - if set to false isURL will return false if fragments are present.
`allow_query_components` - if set to false isURL will return false if query components are present.
`validate_length` - if set to false isURL will skip string length validation. `max_allowed_length` will be ignored if this is set as `false`.
`max_allowed_length` - if set isURL will not allow URLs longer than the specified value (default is 2084 that IE maximum URL length). | +| **isULID(str)** | check if the string is a [ULID](https://github.com/ulid/spec). | +| **isUUID(str [, version])** | check if the string is an RFC9562 UUID.
`version` is one of `'1'`-`'8'`, `'nil'`, `'max'`, or `'all'`. | +| **isVariableWidth(str)** | check if the string contains a mixture of full and half-width chars. | +| **isVAT(str, countryCode)** | check if the string is a [valid VAT number][VAT Number] if validation is available for the given country code matching [ISO 3166-1 alpha-2][ISO 3166-1 alpha-2].

`countryCode` is one of `['AL', 'AR', 'AT', 'AU', 'BE', 'BG', 'BO', 'BR', 'BY', 'CA', 'CH', 'CL', 'CO', 'CR', 'CY', 'CZ', 'DE', 'DK', 'DO', 'EC', 'EE', 'EL', 'ES', 'FI', 'FR', 'GB', 'GT', 'HN', 'HR', 'HU', 'ID', 'IE', 'IL', 'IN', 'IS', 'IT', 'KZ', 'LT', 'LU', 'LV', 'MK', 'MT', 'MX', 'NG', 'NI', 'NL', 'NO', 'NZ', 'PA', 'PE', 'PH', 'PL', 'PT', 'PY', 'RO', 'RS', 'RU', 'SA', 'SE', 'SI', 'SK', 'SM', 'SV', 'TR', 'UA', 'UY', 'UZ', 'VE']`. | +| **isWhitelisted(str, chars)** | check if the string consists only of characters that appear in the whitelist `chars`. | +| **matches(str, pattern [, modifiers])** | check if the string matches the pattern.

Either `matches('foo', /foo/i)` or `matches('foo', 'foo', 'i')`. | ## Sanitizers Here is a list of the sanitizers currently available. -Sanitizer | Description --------------------------------------- | ------------------------------- -**blacklist(input, chars)** | remove characters that appear in the blacklist. The characters are used in a RegExp and so you will need to escape some chars, e.g. `blacklist(input, '\\[\\]')`. -**escape(input)** | replace `<`, `>`, `&`, `'`, `"` and `/` with HTML entities. -**ltrim(input [, chars])** | trim characters from the left-side of the input. -**normalizeEmail(email [, options])** | canonicalize an email address. (This doesn't validate that the input is an email, if you want to validate the email use isEmail beforehand).

`options` is an object with the following keys and default values:
  • *all_lowercase: true* - Transforms the local part (before the @ symbol) of all email addresses to lowercase. Please note that this may violate RFC 5321, which gives providers the possibility to treat the local part of email addresses in a case sensitive way (although in practice most - yet not all - providers don't). The domain part of the email address is always lowercased, as it is case insensitive per RFC 1035.
  • *gmail_lowercase: true* - Gmail addresses are known to be case-insensitive, so this switch allows lowercasing them even when *all_lowercase* is set to false. Please note that when *all_lowercase* is true, Gmail addresses are lowercased regardless of the value of this setting.
  • *gmail_remove_dots: true*: Removes dots from the local part of the email address, as Gmail ignores them (e.g. "john.doe" and "johndoe" are considered equal).
  • *gmail_remove_subaddress: true*: Normalizes addresses by removing "sub-addresses", which is the part following a "+" sign (e.g. "foo+bar@gmail.com" becomes "foo@gmail.com").
  • *gmail_convert_googlemaildotcom: true*: Converts addresses with domain @googlemail.com to @gmail.com, as they're equivalent.
  • *outlookdotcom_lowercase: true* - Outlook.com addresses (including Windows Live and Hotmail) are known to be case-insensitive, so this switch allows lowercasing them even when *all_lowercase* is set to false. Please note that when *all_lowercase* is true, Outlook.com addresses are lowercased regardless of the value of this setting.
  • *outlookdotcom_remove_subaddress: true*: Normalizes addresses by removing "sub-addresses", which is the part following a "+" sign (e.g. "foo+bar@outlook.com" becomes "foo@outlook.com").
  • *yahoo_lowercase: true* - Yahoo Mail addresses are known to be case-insensitive, so this switch allows lowercasing them even when *all_lowercase* is set to false. Please note that when *all_lowercase* is true, Yahoo Mail addresses are lowercased regardless of the value of this setting.
  • *yahoo_remove_subaddress: true*: Normalizes addresses by removing "sub-addresses", which is the part following a "-" sign (e.g. "foo-bar@yahoo.com" becomes "foo@yahoo.com").
  • *icloud_lowercase: true* - iCloud addresses (including MobileMe) are known to be case-insensitive, so this switch allows lowercasing them even when *all_lowercase* is set to false. Please note that when *all_lowercase* is true, iCloud addresses are lowercased regardless of the value of this setting.
  • *icloud_remove_subaddress: true*: Normalizes addresses by removing "sub-addresses", which is the part following a "+" sign (e.g. "foo+bar@icloud.com" becomes "foo@icloud.com").
-**rtrim(input [, chars])** | trim characters from the right-side of the input. -**stripLow(input [, keep_new_lines])** | remove characters with a numerical value < 32 and 127, mostly control characters. If `keep_new_lines` is `true`, newline characters are preserved (`\n` and `\r`, hex `0xA` and `0xD`). Unicode-safe in JavaScript. -**toBoolean(input [, strict])** | convert the input string to a boolean. Everything except for `'0'`, `'false'` and `''` returns `true`. In strict mode only `'1'` and `'true'` return `true`. -**toDate(input)** | convert the input string to a date, or `null` if the input is not a date. -**toFloat(input)** | convert the input string to a float, or `NaN` if the input is not a float. -**toInt(input [, radix])** | convert the input string to an integer, or `NaN` if the input is not an integer. -**trim(input [, chars])** | trim characters (whitespace by default) from both sides of the input. -**unescape(input)** | replace HTML encoded entities with `<`, `>`, `&`, `'`, `"` and `/`. -**whitelist(input, chars)** | remove characters that do not appear in the whitelist. The characters are used in a RegExp and so you will need to escape some chars, e.g. `whitelist(input, '\\[\\]')`. +| Sanitizer | Description | +| -------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| **blacklist(input, chars)** | remove characters that appear in the blacklist. The characters are used in a RegExp and so you will need to escape some chars, e.g. `blacklist(input, '\\[\\]')`. | +| **escape(input)** | replace `<`, `>`, `&`, `'`, `"`, `` ` ``, `\` and `/` with HTML entities. | +| **ltrim(input [, chars])** | trim characters from the left-side of the input. | +| **normalizeEmail(email [, options])** | canonicalize an email address. (This doesn't validate that the input is an email, if you want to validate the email use isEmail beforehand).

`options` is an object with the following keys and default values:
  • _all_lowercase: true_ - Transforms the local part (before the @ symbol) of all email addresses to lowercase. Please note that this may violate RFC 5321, which gives providers the possibility to treat the local part of email addresses in a case sensitive way (although in practice most - yet not all - providers don't). The domain part of the email address is always lowercased, as it is case insensitive per RFC 1035.
  • _gmail_lowercase: true_ - Gmail addresses are known to be case-insensitive, so this switch allows lowercasing them even when _all_lowercase_ is set to false. Please note that when _all_lowercase_ is true, Gmail addresses are lowercased regardless of the value of this setting.
  • _gmail_remove_dots: true_: Removes dots from the local part of the email address, as Gmail ignores them (e.g. "john.doe" and "johndoe" are considered equal).
  • _gmail_remove_subaddress: true_: Normalizes addresses by removing "sub-addresses", which is the part following a "+" sign (e.g. "foo+bar@gmail.com" becomes "foo@gmail.com").
  • _gmail_convert_googlemaildotcom: true_: Converts addresses with domain @googlemail.com to @gmail.com, as they're equivalent.
  • _outlookdotcom_lowercase: true_ - Outlook.com addresses (including Windows Live and Hotmail) are known to be case-insensitive, so this switch allows lowercasing them even when _all_lowercase_ is set to false. Please note that when _all_lowercase_ is true, Outlook.com addresses are lowercased regardless of the value of this setting.
  • _outlookdotcom_remove_subaddress: true_: Normalizes addresses by removing "sub-addresses", which is the part following a "+" sign (e.g. "foo+bar@outlook.com" becomes "foo@outlook.com").
  • _yahoo_lowercase: true_ - Yahoo Mail addresses are known to be case-insensitive, so this switch allows lowercasing them even when _all_lowercase_ is set to false. Please note that when _all_lowercase_ is true, Yahoo Mail addresses are lowercased regardless of the value of this setting.
  • _yahoo_remove_subaddress: true_: Normalizes addresses by removing "sub-addresses", which is the part following a "-" sign (e.g. "foo-bar@yahoo.com" becomes "foo@yahoo.com").
  • _icloud_lowercase: true_ - iCloud addresses (including MobileMe) are known to be case-insensitive, so this switch allows lowercasing them even when _all_lowercase_ is set to false. Please note that when _all_lowercase_ is true, iCloud addresses are lowercased regardless of the value of this setting.
  • _icloud_remove_subaddress: true_: Normalizes addresses by removing "sub-addresses", which is the part following a "+" sign (e.g. "foo+bar@icloud.com" becomes "foo@icloud.com").
| +| **rtrim(input [, chars])** | trim characters from the right-side of the input. | +| **stripLow(input [, keep_new_lines])** | remove characters with a numerical value < 32 and 127, mostly control characters. If `keep_new_lines` is `true`, newline characters are preserved (`\n` and `\r`, hex `0xA` and `0xD`). Unicode-safe in JavaScript. | +| **toBoolean(input [, strict])** | convert the input string to a boolean. Everything except for `'0'`, `'false'` and `''` returns `true`. In strict mode only `'1'` and `'true'` return `true`. | +| **toDate(input)** | convert the input string to a date, or `null` if the input is not a date. | +| **toFloat(input)** | convert the input string to a float, or `NaN` if the input is not a float. | +| **toInt(input [, radix])** | convert the input string to an integer, or `NaN` if the input is not an integer. | +| **trim(input [, chars])** | trim characters (whitespace by default) from both sides of the input. | +| **unescape(input)** | replace HTML encoded entities with `<`, `>`, `&`, `'`, `"`, `` ` ``, `\` and `/`. | +| **whitelist(input, chars)** | remove characters that do not appear in the whitelist. The characters are used in a RegExp and so you will need to escape some chars, e.g. `whitelist(input, '\\[\\]')`. | ### XSS Sanitization @@ -201,37 +202,12 @@ XSS sanitization was removed from the library in [2d5d6999](https://github.com/v For an alternative, have a look at Yahoo's [xss-filters library](https://github.com/yahoo/xss-filters) or at [DOMPurify](https://github.com/cure53/DOMPurify). -## Contributing - -In general, we follow the "fork-and-pull" Git workflow. - -1. Fork the repo on GitHub -2. Clone the project to your own machine -3. Work on your fork - 1. Make your changes and additions - - Most of your changes should be focused on `src/` and `test/` folders and/or `README.md`. - - Files such as `validator.js`, `validator.min.js` and files in `lib/` folder are autogenerated when running tests (`npm test`) and need not to be changed **manually**. - 2. Change or add tests if needed - 3. Run tests and make sure they pass - 4. Add changes to README.md if needed -4. Commit changes to your own branch -5. **Make sure** you merge the latest from "upstream" and resolve conflicts if there is any -6. Repeat step 3(3) above -7. Push your work back up to your fork -8. Submit a Pull request so that we can review your changes - -## Tests - -Tests are using mocha, to run the tests use: - -```sh -$ npm test -``` - ## Maintainers - [chriso](https://github.com/chriso) - **Chris O'Hara** (author) - [profnandaa](https://github.com/profnandaa) - **Anthony Nandaa** +- [rubiin](https://github.com/rubiin) - **Rubin Bhandari** +- [wikirik](https://github.com/wikirik) - **Rik Smale** - [ezkemboi](https://github.com/ezkemboi) - **Ezrqn Kemboi** - [tux-tn](https://github.com/tux-tn) - **Sarhan Aissi** @@ -239,51 +215,27 @@ $ npm test Remember, validating can be troublesome sometimes. See [A list of articles about programming assumptions commonly made that aren't true](https://github.com/jameslk/awesome-falsehoods). -## License (MIT) +## Contributing + +We welcome contributions from the community! If you're interested in contributing to this project, please read our [Contribution Guide](CONTRIBUTING.md) to get started. -``` -Copyright (c) 2018 Chris O'Hara - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -``` +## License -[downloads-image]: http://img.shields.io/npm/dm/validator.svg +This project is licensed under the [MIT](LICENSE). See the [LICENSE](LICENSE) file for details. +[downloads-image]: http://img.shields.io/npm/dm/validator.svg [npm-url]: https://npmjs.org/package/validator [npm-image]: http://img.shields.io/npm/v/validator.svg - [codecov-url]: https://codecov.io/gh/validatorjs/validator.js [codecov-image]: https://codecov.io/gh/validatorjs/validator.js/branch/master/graph/badge.svg - [ci-url]: https://github.com/validatorjs/validator.js/actions?query=workflow%3ACI [ci-image]: https://github.com/validatorjs/validator.js/workflows/CI/badge.svg?branch=master - [gitter-url]: https://gitter.im/validatorjs/community [gitter-image]: https://badges.gitter.im/validatorjs/community.svg - [huntr-url]: https://huntr.dev/bounties/disclose/?target=https://github.com/validatorjs/validator.js [huntr-image]: https://cdn.huntr.dev/huntr_security_badge_mono.svg - [amd]: http://requirejs.org/docs/whyamd.html [bower]: http://bower.io/ - [Crockford Base32]: http://www.crockford.com/base32.html [Base64 URL Safe]: https://base64.guru/standards/base64url [Data URI Format]: https://developer.mozilla.org/en-US/docs/Web/HTTP/data_URIs @@ -295,8 +247,10 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. [ISIN]: https://en.wikipedia.org/wiki/International_Securities_Identification_Number [ISO 639-1]: https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes [ISO 8601]: https://en.wikipedia.org/wiki/ISO_8601 +[ISO 15924]: https://en.wikipedia.org/wiki/ISO_15924 [ISO 3166-1 alpha-2]: https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2 [ISO 3166-1 alpha-3]: https://en.wikipedia.org/wiki/ISO_3166-1_alpha-3 +[ISO 3166-1 numeric]: https://en.wikipedia.org/wiki/ISO_3166-1_numeric [ISO 4217]: https://en.wikipedia.org/wiki/ISO_4217 [ISRC]: https://en.wikipedia.org/wiki/International_Standard_Recording_Code [ISSN]: https://en.wikipedia.org/wiki/International_Standard_Serial_Number diff --git a/SECURITY.md b/SECURITY.md index 72592f135..266d8d844 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -8,4 +8,4 @@ In the case of a confirmed security issue, only the current version of validator **Please don't disclose security-related issues publicly.** -If you discover a vulnerability within validator, please use [huntr.dev disclosure form](https://huntr.dev/bounties/disclose/?target=https://github.com/validatorjs/validator.js). We will try to validate and respond to reports in a reasonable time. if the issue is confirmed, we will create a security advisory and a patch as soon as possible. \ No newline at end of file +Report the security issue to the Node.js Security Working Group through the [HackerOne program](https://hackerone.com/nodejs-ecosystem) for ecosystem modules on npm, or to [Snyk Security Team](https://snyk.io/vulnerability-disclosure). They will help triage the security issue and work with all involved parties to remediate and release a fix. diff --git a/package.json b/package.json index 153e5c1a4..49ac0f81f 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "validator", "description": "String validation and sanitization", - "version": "13.11.0", + "version": "13.15.0", "sideEffects": false, "homepage": "https://github.com/validatorjs/validator.js", "files": [ diff --git a/src/index.js b/src/index.js index bef4cfff4..c47674595 100644 --- a/src/index.js +++ b/src/index.js @@ -18,10 +18,11 @@ import isTime from './lib/isTime'; import isBoolean from './lib/isBoolean'; import isLocale from './lib/isLocale'; +import isAbaRouting from './lib/isAbaRouting'; import isAlpha, { locales as isAlphaLocales } from './lib/isAlpha'; import isAlphanumeric, { locales as isAlphanumericLocales } from './lib/isAlphanumeric'; import isNumeric from './lib/isNumeric'; -import isPassportNumber from './lib/isPassportNumber'; +import isPassportNumber, { locales as passportNumberLocales } from './lib/isPassportNumber'; import isPort from './lib/isPort'; import isLowercase from './lib/isLowercase'; import isUppercase from './lib/isUppercase'; @@ -62,6 +63,7 @@ import isEmpty from './lib/isEmpty'; import isLength from './lib/isLength'; import isByteLength from './lib/isByteLength'; +import isULID from './lib/isULID'; import isUUID from './lib/isUUID'; import isMongoId from './lib/isMongoId'; @@ -92,8 +94,10 @@ import { isISO6346, isFreightContainerID } from './lib/isISO6346'; import isISO6391 from './lib/isISO6391'; import isISO8601 from './lib/isISO8601'; import isRFC3339 from './lib/isRFC3339'; +import isISO15924 from './lib/isISO15924'; import isISO31661Alpha2 from './lib/isISO31661Alpha2'; import isISO31661Alpha3 from './lib/isISO31661Alpha3'; +import isISO31661Numeric from './lib/isISO31661Numeric'; import isISO4217 from './lib/isISO4217'; import isBase32 from './lib/isBase32'; @@ -126,7 +130,7 @@ import isStrongPassword from './lib/isStrongPassword'; import isVAT from './lib/isVAT'; -const version = '13.11.0'; +const version = '13.15.0'; const validator = { version, @@ -146,12 +150,14 @@ const validator = { isBoolean, isIBAN, isBIC, + isAbaRouting, isAlpha, isAlphaLocales, isAlphanumeric, isAlphanumericLocales, isNumeric, isPassportNumber, + passportNumberLocales, isPort, isLowercase, isUppercase, @@ -182,6 +188,7 @@ const validator = { isLength, isLocale, isByteLength, + isULID, isUUID, isMongoId, isAfter, @@ -205,9 +212,11 @@ const validator = { isFreightContainerID, isISO6391, isISO8601, + isISO15924, isRFC3339, isISO31661Alpha2, isISO31661Alpha3, + isISO31661Numeric, isISO4217, isBase32, isBase58, diff --git a/src/lib/alpha.js b/src/lib/alpha.js index d540ed1cf..91ae933a5 100644 --- a/src/lib/alpha.js +++ b/src/lib/alpha.js @@ -10,6 +10,7 @@ export const alpha = { 'fa-IR': /^[ابپتثجچحخدذرزژسشصضطظعغفقکگلمنوهی]+$/i, 'fi-FI': /^[A-ZÅÄÖ]+$/i, 'fr-FR': /^[A-ZÀÂÆÇÉÈÊËÏÎÔŒÙÛÜŸ]+$/i, + 'ga-IE': /^[A-ZÁÉÍÓÚ]+$/i, 'it-IT': /^[A-ZÀÉÈÌÎÓÒÙ]+$/i, 'ja-JP': /^[ぁ-んァ-ヶヲ-゚一-龠ー・。、]+$/i, 'nb-NO': /^[A-ZÆØÅ]+$/i, @@ -35,6 +36,7 @@ export const alpha = { he: /^[א-ת]+$/, fa: /^['آاءأؤئبپتثجچحخدذرزژسشصضطظعغفقکگلمنوهةی']+$/i, bn: /^['ঀঁংঃঅআইঈউঊঋঌএঐওঔকখগঘঙচছজঝঞটঠডঢণতথদধনপফবভমযরলশষসহ়ঽািীুূৃৄেৈোৌ্ৎৗড়ঢ়য়ৠৡৢৣৰৱ৲৳৴৵৶৷৸৹৺৻']+$/, + eo: /^[ABCĈD-GĜHĤIJĴK-PRSŜTUŬVZ]+$/i, 'hi-IN': /^[\u0900-\u0961]+[\u0972-\u097F]*$/i, 'si-LK': /^[\u0D80-\u0DFF]+$/, }; @@ -50,6 +52,7 @@ export const alphanumeric = { 'es-ES': /^[0-9A-ZÁÉÍÑÓÚÜ]+$/i, 'fi-FI': /^[0-9A-ZÅÄÖ]+$/i, 'fr-FR': /^[0-9A-ZÀÂÆÇÉÈÊËÏÎÔŒÙÛÜŸ]+$/i, + 'ga-IE': /^[0-9A-ZÁÉÍÓÚ]+$/i, 'it-IT': /^[0-9A-ZÀÉÈÌÎÓÒÙ]+$/i, 'ja-JP': /^[0-90-9ぁ-んァ-ヶヲ-゚一-龠ー・。、]+$/i, 'hu-HU': /^[0-9A-ZÁÉÍÓÖŐÚÜŰ]+$/i, @@ -75,6 +78,7 @@ export const alphanumeric = { he: /^[0-9א-ת]+$/, fa: /^['0-9آاءأؤئبپتثجچحخدذرزژسشصضطظعغفقکگلمنوهةی۱۲۳۴۵۶۷۸۹۰']+$/i, bn: /^['ঀঁংঃঅআইঈউঊঋঌএঐওঔকখগঘঙচছজঝঞটঠডঢণতথদধনপফবভমযরলশষসহ়ঽািীুূৃৄেৈোৌ্ৎৗড়ঢ়য়ৠৡৢৣ০১২৩৪৫৬৭৮৯ৰৱ৲৳৴৵৶৷৸৹৺৻']+$/, + eo: /^[0-9ABCĈD-GĜHĤIJĴK-PRSŜTUŬVZ]+$/i, 'hi-IN': /^[\u0900-\u0963]+[\u0966-\u097F]*$/i, 'si-LK': /^[0-9\u0D80-\u0DFF]+$/, }; @@ -125,7 +129,7 @@ for (let locale, i = 0; i < bengaliLocales.length; i++) { // Source: https://en.wikipedia.org/wiki/Decimal_mark export const dotDecimal = ['ar-EG', 'ar-LB', 'ar-LY']; export const commaDecimal = [ - 'bg-BG', 'cs-CZ', 'da-DK', 'de-DE', 'el-GR', 'en-ZM', 'es-ES', 'fr-CA', 'fr-FR', + 'bg-BG', 'cs-CZ', 'da-DK', 'de-DE', 'el-GR', 'en-ZM', 'eo', 'es-ES', 'fr-CA', 'fr-FR', 'id-ID', 'it-IT', 'ku-IQ', 'hi-IN', 'hu-HU', 'nb-NO', 'nn-NO', 'nl-NL', 'pl-PL', 'pt-PT', 'ru-RU', 'kk-KZ', 'si-LK', 'sl-SI', 'sr-RS@latin', 'sr-RS', 'sv-SE', 'tr-TR', 'uk-UA', 'vi-VN', ]; diff --git a/src/lib/contains.js b/src/lib/contains.js index 7be314b04..8e716c4be 100644 --- a/src/lib/contains.js +++ b/src/lib/contains.js @@ -2,14 +2,14 @@ import assertString from './util/assertString'; import toString from './util/toString'; import merge from './util/merge'; -const defaulContainsOptions = { +const defaultContainsOptions = { ignoreCase: false, minOccurrences: 1, }; export default function contains(str, elem, options) { assertString(str); - options = merge(options, defaulContainsOptions); + options = merge(options, defaultContainsOptions); if (options.ignoreCase) { return str.toLowerCase().split(toString(elem).toLowerCase()).length > options.minOccurrences; diff --git a/src/lib/isAbaRouting.js b/src/lib/isAbaRouting.js new file mode 100644 index 000000000..0c6fd7fb2 --- /dev/null +++ b/src/lib/isAbaRouting.js @@ -0,0 +1,20 @@ +import assertString from './util/assertString'; + +// http://www.brainjar.com/js/validation/ +// https://www.aba.com/news-research/research-analysis/routing-number-policy-procedures +// series reserved for future use are excluded +const isRoutingReg = /^(?!(1[3-9])|(20)|(3[3-9])|(4[0-9])|(5[0-9])|(60)|(7[3-9])|(8[1-9])|(9[0-2])|(9[3-9]))[0-9]{9}$/; + +export default function isAbaRouting(str) { + assertString(str); + + if (!isRoutingReg.test(str)) return false; + + let checkSumVal = 0; + for (let i = 0; i < str.length; i++) { + if (i % 3 === 0) checkSumVal += str[i] * 3; + else if (i % 3 === 1) checkSumVal += str[i] * 7; + else checkSumVal += str[i] * 1; + } + return (checkSumVal % 10 === 0); +} diff --git a/src/lib/isAfter.js b/src/lib/isAfter.js index e116e77ce..149622a0d 100644 --- a/src/lib/isAfter.js +++ b/src/lib/isAfter.js @@ -3,9 +3,10 @@ import toDate from './toDate'; export default function isAfter(date, options) { // For backwards compatibility: // isAfter(str [, date]), i.e. `options` could be used as argument for the legacy `date` - const comparisonDate = options?.comparisonDate || options || Date().toString(); + const comparisonDate = (typeof options === 'object' ? options.comparisonDate : options) || Date().toString(); const comparison = toDate(comparisonDate); const original = toDate(date); + return !!(original && comparison && original > comparison); } diff --git a/src/lib/isBase64.js b/src/lib/isBase64.js index 02dead0f4..7eb3a5b56 100644 --- a/src/lib/isBase64.js +++ b/src/lib/isBase64.js @@ -1,28 +1,23 @@ import assertString from './util/assertString'; import merge from './util/merge'; -const notBase64 = /[^A-Z0-9+\/=]/i; -const urlSafeBase64 = /^[A-Z0-9_\-]*$/i; - -const defaultBase64Options = { - urlSafe: false, -}; +const base64WithPadding = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{4})$/; +const base64WithoutPadding = /^[A-Za-z0-9+/]+$/; +const base64UrlWithPadding = /^(?:[A-Za-z0-9_-]{4})*(?:[A-Za-z0-9_-]{2}==|[A-Za-z0-9_-]{3}=|[A-Za-z0-9_-]{4})$/; +const base64UrlWithoutPadding = /^[A-Za-z0-9_-]+$/; export default function isBase64(str, options) { assertString(str); - options = merge(options, defaultBase64Options); - const len = str.length; + options = merge(options, { urlSafe: false, padding: !options?.urlSafe }); - if (options.urlSafe) { - return urlSafeBase64.test(str); - } + if (str === '') return true; - if (len % 4 !== 0 || notBase64.test(str)) { - return false; + let regex; + if (options.urlSafe) { + regex = options.padding ? base64UrlWithPadding : base64UrlWithoutPadding; + } else { + regex = options.padding ? base64WithPadding : base64WithoutPadding; } - const firstPaddingChar = str.indexOf('='); - return firstPaddingChar === -1 || - firstPaddingChar === len - 1 || - (firstPaddingChar === len - 2 && str[len - 1] === '='); + return (!options.padding || str.length % 4 === 0) && regex.test(str); } diff --git a/src/lib/isBefore.js b/src/lib/isBefore.js index 8314f0e14..977d0ad1a 100644 --- a/src/lib/isBefore.js +++ b/src/lib/isBefore.js @@ -1,9 +1,12 @@ -import assertString from './util/assertString'; import toDate from './toDate'; -export default function isBefore(str, date = String(new Date())) { - assertString(str); - const comparison = toDate(date); - const original = toDate(str); +export default function isBefore(date, options) { + // For backwards compatibility: + // isBefore(str [, date]), i.e. `options` could be used as argument for the legacy `date` + const comparisonDate = (typeof options === 'object' ? options.comparisonDate : options) || Date().toString(); + + const comparison = toDate(comparisonDate); + const original = toDate(date); + return !!(original && comparison && original < comparison); } diff --git a/src/lib/isBtcAddress.js b/src/lib/isBtcAddress.js index 08f12f4ca..1a309e682 100644 --- a/src/lib/isBtcAddress.js +++ b/src/lib/isBtcAddress.js @@ -1,7 +1,7 @@ import assertString from './util/assertString'; -const bech32 = /^(bc1)[a-z0-9]{25,39}$/; -const base58 = /^(1|3)[A-HJ-NP-Za-km-z1-9]{25,39}$/; +const bech32 = /^(bc1|tb1|bc1p|tb1p)[ac-hj-np-z02-9]{39,58}$/; +const base58 = /^(1|2|3|m)[A-HJ-NP-Za-km-z1-9]{25,39}$/; export default function isBtcAddress(str) { assertString(str); diff --git a/src/lib/isDate.js b/src/lib/isDate.js index f0b28917a..3a1e4afd2 100644 --- a/src/lib/isDate.js +++ b/src/lib/isDate.js @@ -12,7 +12,7 @@ function isValidFormat(format) { function zip(date, format) { const zippedArr = [], - len = Math.min(date.length, format.length); + len = Math.max(date.length, format.length); for (let i = 0; i < len; i++) { zippedArr.push([date[i], format[i]]); @@ -22,12 +22,13 @@ function zip(date, format) { } export default function isDate(input, options) { - if (typeof options === 'string') { // Allow backward compatbility for old format isDate(input [, format]) + if (typeof options === 'string') { // Allow backward compatibility for old format isDate(input [, format]) options = merge({ format: options }, default_date_options); } else { options = merge(options, default_date_options); } if (typeof input === 'string' && isValidFormat(options.format)) { + if (options.strictMode && input.length !== options.format.length) return false; const formatDelimiter = options.delimiters .find(delimiter => options.format.indexOf(delimiter) !== -1); const dateDelimiter = options.strictMode @@ -40,7 +41,7 @@ export default function isDate(input, options) { const dateObj = {}; for (const [dateWord, formatWord] of dateAndFormat) { - if (dateWord.length !== formatWord.length) { + if (!dateWord || !formatWord || dateWord.length !== formatWord.length) { return false; } @@ -49,6 +50,11 @@ export default function isDate(input, options) { let fullYear = dateObj.y; + // Check if the year starts with a hyphen + if (fullYear.startsWith('-')) { + return false; // Hyphen before year is not allowed + } + if (dateObj.y.length === 2) { const parsedYear = parseInt(dateObj.y, 10); diff --git a/src/lib/isEAN.js b/src/lib/isEAN.js index 968c385dd..731932ad3 100644 --- a/src/lib/isEAN.js +++ b/src/lib/isEAN.js @@ -15,9 +15,9 @@ import assertString from './util/assertString'; /** - * Define EAN Lenghts; 8 for EAN-8; 13 for EAN-13; 14 for EAN-14 + * Define EAN Lengths; 8 for EAN-8; 13 for EAN-13; 14 for EAN-14 * and Regular Expression for valid EANs (EAN-8, EAN-13, EAN-14), - * with exact numberic matching of 8 or 13 or 14 digits [0-9] + * with exact numeric matching of 8 or 13 or 14 digits [0-9] */ const LENGTH_EAN_8 = 8; const LENGTH_EAN_14 = 14; diff --git a/src/lib/isEmail.js b/src/lib/isEmail.js index 12938765e..abe465052 100644 --- a/src/lib/isEmail.js +++ b/src/lib/isEmail.js @@ -1,4 +1,5 @@ import assertString from './util/assertString'; +import checkHost from './util/checkHost'; import isByteLength from './isByteLength'; import isFQDN from './isFQDN'; @@ -60,7 +61,6 @@ function validateDisplayName(display_name) { return true; } - export default function isEmail(str, options) { assertString(str); options = merge(options, default_email_options); @@ -97,11 +97,11 @@ export default function isEmail(str, options) { const domain = parts.pop(); const lower_domain = domain.toLowerCase(); - if (options.host_blacklist.includes(lower_domain)) { + if (options.host_blacklist.length > 0 && checkHost(lower_domain, options.host_blacklist)) { return false; } - if (options.host_whitelist.length > 0 && !options.host_whitelist.includes(lower_domain)) { + if (options.host_whitelist.length > 0 && !checkHost(lower_domain, options.host_whitelist)) { return false; } @@ -109,11 +109,11 @@ export default function isEmail(str, options) { if (options.domain_specific_validation && (lower_domain === 'gmail.com' || lower_domain === 'googlemail.com')) { /* - Previously we removed dots for gmail addresses before validating. - This was removed because it allows `multiple..dots@gmail.com` - to be reported as valid, but it is not. - Gmail only normalizes single dots, removing them from here is pointless, - should be done in normalizeEmail + Previously we removed dots for gmail addresses before validating. + This was removed because it allows `multiple..dots@gmail.com` + to be reported as valid, but it is not. + Gmail only normalizes single dots, removing them from here is pointless, + should be done in normalizeEmail */ user = user.toLowerCase(); @@ -162,7 +162,11 @@ export default function isEmail(str, options) { } } - if (user[0] === '"') { + if (options.blacklisted_chars) { + if (user.search(new RegExp(`[${options.blacklisted_chars}]+`, 'g')) !== -1) return false; + } + + if (user[0] === '"' && user[user.length - 1] === '"') { user = user.slice(1, user.length - 1); return options.allow_utf8_local_part ? quotedEmailUserUtf8.test(user) : @@ -178,9 +182,6 @@ export default function isEmail(str, options) { return false; } } - if (options.blacklisted_chars) { - if (user.search(new RegExp(`[${options.blacklisted_chars}]+`, 'g')) !== -1) return false; - } return true; } diff --git a/src/lib/isFloat.js b/src/lib/isFloat.js index 643f9729f..84bdc782c 100644 --- a/src/lib/isFloat.js +++ b/src/lib/isFloat.js @@ -1,4 +1,5 @@ import assertString from './util/assertString'; +import isNullOrUndefined from './util/nullUndefinedCheck'; import { decimal } from './alpha'; export default function isFloat(str, options) { @@ -10,10 +11,10 @@ export default function isFloat(str, options) { } const value = parseFloat(str.replace(',', '.')); return float.test(str) && - (!options.hasOwnProperty('min') || value >= options.min) && - (!options.hasOwnProperty('max') || value <= options.max) && - (!options.hasOwnProperty('lt') || value < options.lt) && - (!options.hasOwnProperty('gt') || value > options.gt); + (!options.hasOwnProperty('min') || isNullOrUndefined(options.min) || value >= options.min) && + (!options.hasOwnProperty('max') || isNullOrUndefined(options.max) || value <= options.max) && + (!options.hasOwnProperty('lt') || isNullOrUndefined(options.lt) || value < options.lt) && + (!options.hasOwnProperty('gt') || isNullOrUndefined(options.gt) || value > options.gt); } export const locales = Object.keys(decimal); diff --git a/src/lib/isIBAN.js b/src/lib/isIBAN.js index dd226b1da..94ac67ca5 100644 --- a/src/lib/isIBAN.js +++ b/src/lib/isIBAN.js @@ -24,6 +24,7 @@ const ibanRegexThroughCountryCode = { DE: /^(DE[0-9]{2})\d{18}$/, DK: /^(DK[0-9]{2})\d{14}$/, DO: /^(DO[0-9]{2})[A-Z]{4}\d{20}$/, + DZ: /^(DZ\d{24})$/, EE: /^(EE[0-9]{2})\d{16}$/, EG: /^(EG[0-9]{2})\d{25}$/, ES: /^(ES[0-9]{2})\d{20}$/, @@ -38,7 +39,7 @@ const ibanRegexThroughCountryCode = { GT: /^(GT[0-9]{2})[A-Z0-9]{4}[A-Z0-9]{20}$/, HR: /^(HR[0-9]{2})\d{17}$/, HU: /^(HU[0-9]{2})\d{24}$/, - IE: /^(IE[0-9]{2})[A-Z0-9]{4}\d{14}$/, + IE: /^(IE[0-9]{2})[A-Z]{4}\d{14}$/, IL: /^(IL[0-9]{2})\d{19}$/, IQ: /^(IQ[0-9]{2})[A-Z]{4}\d{15}$/, IR: /^(IR[0-9]{2})0\d{2}0\d{18}$/, @@ -66,7 +67,7 @@ const ibanRegexThroughCountryCode = { NO: /^(NO[0-9]{2})\d{11}$/, PK: /^(PK[0-9]{2})[A-Z0-9]{4}\d{16}$/, PL: /^(PL[0-9]{2})\d{24}$/, - PS: /^(PS[0-9]{2})[A-Z0-9]{4}\d{21}$/, + PS: /^(PS[0-9]{2})[A-Z]{4}[A-Z0-9]{21}$/, PT: /^(PT[0-9]{2})\d{21}$/, QA: /^(QA[0-9]{2})[A-Z]{4}[A-Z0-9]{21}$/, RO: /^(RO[0-9]{2})[A-Z]{4}[A-Z0-9]{16}$/, @@ -83,7 +84,7 @@ const ibanRegexThroughCountryCode = { TR: /^(TR[0-9]{2})\d{5}[A-Z0-9]{17}$/, UA: /^(UA[0-9]{2})\d{6}[A-Z0-9]{19}$/, VA: /^(VA[0-9]{2})\d{18}$/, - VG: /^(VG[0-9]{2})[A-Z0-9]{4}\d{16}$/, + VG: /^(VG[0-9]{2})[A-Z]{4}\d{16}$/, XK: /^(XK[0-9]{2})\d{16}$/, }; diff --git a/src/lib/isIMEI.js b/src/lib/isIMEI.js index fb97d4924..984b4fb88 100644 --- a/src/lib/isIMEI.js +++ b/src/lib/isIMEI.js @@ -1,8 +1,8 @@ import assertString from './util/assertString'; -let imeiRegexWithoutHypens = /^[0-9]{15}$/; -let imeiRegexWithHypens = /^\d{2}-\d{6}-\d{6}-\d{1}$/; +let imeiRegexWithoutHyphens = /^[0-9]{15}$/; +let imeiRegexWithHyphens = /^\d{2}-\d{6}-\d{6}-\d{1}$/; export default function isIMEI(str, options) { @@ -11,10 +11,10 @@ export default function isIMEI(str, options) { // default regex for checking imei is the one without hyphens - let imeiRegex = imeiRegexWithoutHypens; + let imeiRegex = imeiRegexWithoutHyphens; if (options.allow_hyphens) { - imeiRegex = imeiRegexWithHypens; + imeiRegex = imeiRegexWithHyphens; } diff --git a/src/lib/isIP.js b/src/lib/isIP.js index 40ca19aec..da9bb6ca9 100644 --- a/src/lib/isIP.js +++ b/src/lib/isIP.js @@ -42,19 +42,26 @@ const IPv6AddressRegExp = new RegExp('^(' + `(?:${IPv6SegmentFormat}:){2}(?:(:${IPv6SegmentFormat}){0,3}:${IPv4AddressFormat}|(:${IPv6SegmentFormat}){1,5}|:)|` + `(?:${IPv6SegmentFormat}:){1}(?:(:${IPv6SegmentFormat}){0,4}:${IPv4AddressFormat}|(:${IPv6SegmentFormat}){1,6}|:)|` + `(?::((?::${IPv6SegmentFormat}){0,5}:${IPv4AddressFormat}|(?::${IPv6SegmentFormat}){1,7}|:))` + - ')(%[0-9a-zA-Z-.:]{1,})?$'); + ')(%[0-9a-zA-Z.]{1,})?$'); + +export default function isIP(ipAddress, options = {}) { + assertString(ipAddress); + + // accessing 'arguments' for backwards compatibility: isIP(ipAddress [, version]) + // eslint-disable-next-line prefer-rest-params + const version = (typeof options === 'object' ? options.version : arguments[1]) || ''; -export default function isIP(str, version = '') { - assertString(str); - version = String(version); if (!version) { - return isIP(str, 4) || isIP(str, 6); + return isIP(ipAddress, { version: 4 }) || isIP(ipAddress, { version: 6 }); } - if (version === '4') { - return IPv4AddressRegExp.test(str); + + if (version.toString() === '4') { + return IPv4AddressRegExp.test(ipAddress); } - if (version === '6') { - return IPv6AddressRegExp.test(str); + + if (version.toString() === '6') { + return IPv6AddressRegExp.test(ipAddress); } + return false; } diff --git a/src/lib/isISO15924.js b/src/lib/isISO15924.js new file mode 100644 index 000000000..30f9e4a4f --- /dev/null +++ b/src/lib/isISO15924.js @@ -0,0 +1,37 @@ +import assertString from './util/assertString'; + +// from https://www.unicode.org/iso15924/iso15924-codes.html +const validISO15924Codes = new Set([ + 'Adlm', 'Afak', 'Aghb', 'Ahom', 'Arab', 'Aran', 'Armi', 'Armn', 'Avst', + 'Bali', 'Bamu', 'Bass', 'Batk', 'Beng', 'Bhks', 'Blis', 'Bopo', 'Brah', 'Brai', 'Bugi', 'Buhd', + 'Cakm', 'Cans', 'Cari', 'Cham', 'Cher', 'Chis', 'Chrs', 'Cirt', 'Copt', 'Cpmn', 'Cprt', 'Cyrl', 'Cyrs', + 'Deva', 'Diak', 'Dogr', 'Dsrt', 'Dupl', + 'Egyd', 'Egyh', 'Egyp', 'Elba', 'Elym', 'Ethi', + 'Gara', 'Geok', 'Geor', 'Glag', 'Gong', 'Gonm', 'Goth', 'Gran', 'Grek', 'Gujr', 'Gukh', 'Guru', + 'Hanb', 'Hang', 'Hani', 'Hano', 'Hans', 'Hant', 'Hatr', 'Hebr', 'Hira', 'Hluw', 'Hmng', 'Hmnp', 'Hrkt', 'Hung', + 'Inds', 'Ital', + 'Jamo', 'Java', 'Jpan', 'Jurc', + 'Kali', 'Kana', 'Kawi', 'Khar', 'Khmr', 'Khoj', 'Kitl', 'Kits', 'Knda', 'Kore', 'Kpel', 'Krai', 'Kthi', + 'Lana', 'Laoo', 'Latf', 'Latg', 'Latn', 'Leke', 'Lepc', 'Limb', 'Lina', 'Linb', 'Lisu', 'Loma', 'Lyci', 'Lydi', + 'Mahj', 'Maka', 'Mand', 'Mani', 'Marc', 'Maya', 'Medf', 'Mend', 'Merc', 'Mero', 'Mlym', 'Modi', 'Mong', 'Moon', 'Mroo', 'Mtei', 'Mult', 'Mymr', + 'Nagm', 'Nand', 'Narb', 'Nbat', 'Newa', 'Nkdb', 'Nkgb', 'Nkoo', 'Nshu', + 'Ogam', 'Olck', 'Onao', 'Orkh', 'Orya', 'Osge', 'Osma', 'Ougr', + 'Palm', 'Pauc', 'Pcun', 'Pelm', 'Perm', 'Phag', 'Phli', 'Phlp', 'Phlv', 'Phnx', 'Plrd', 'Piqd', 'Prti', 'Psin', + 'Qaaa', 'Qaab', 'Qaac', 'Qaad', 'Qaae', 'Qaaf', 'Qaag', 'Qaah', 'Qaai', 'Qaaj', 'Qaak', 'Qaal', 'Qaam', 'Qaan', 'Qaao', 'Qaap', 'Qaaq', 'Qaar', 'Qaas', 'Qaat', 'Qaau', 'Qaav', 'Qaaw', 'Qaax', 'Qaay', 'Qaaz', 'Qaba', 'Qabb', 'Qabc', 'Qabd', 'Qabe', 'Qabf', 'Qabg', 'Qabh', 'Qabi', 'Qabj', 'Qabk', 'Qabl', 'Qabm', 'Qabn', 'Qabo', 'Qabp', 'Qabq', 'Qabr', 'Qabs', 'Qabt', 'Qabu', 'Qabv', 'Qabw', 'Qabx', + 'Ranj', 'Rjng', 'Rohg', 'Roro', 'Runr', + 'Samr', 'Sara', 'Sarb', 'Saur', 'Sgnw', 'Shaw', 'Shrd', 'Shui', 'Sidd', 'Sidt', 'Sind', 'Sinh', 'Sogd', 'Sogo', 'Sora', 'Soyo', 'Sund', 'Sunu', 'Sylo', 'Syrc', 'Syre', 'Syrj', 'Syrn', + 'Tagb', 'Takr', 'Tale', 'Talu', 'Taml', 'Tang', 'Tavt', 'Tayo', 'Telu', 'Teng', 'Tfng', 'Tglg', 'Thaa', 'Thai', 'Tibt', 'Tirh', 'Tnsa', 'Todr', 'Tols', 'Toto', 'Tutg', + 'Ugar', + 'Vaii', 'Visp', 'Vith', + 'Wara', 'Wcho', 'Wole', + 'Xpeo', 'Xsux', + 'Yezi', 'Yiii', + 'Zanb', 'Zinh', 'Zmth', 'Zsye', 'Zsym', 'Zxxx', 'Zyyy', 'Zzzz', +]); + +export default function isISO15924(str) { + assertString(str); + return validISO15924Codes.has(str); +} + +export const ScriptCodes = validISO15924Codes; diff --git a/src/lib/isISO31661Numeric.js b/src/lib/isISO31661Numeric.js new file mode 100644 index 000000000..8b32a8d79 --- /dev/null +++ b/src/lib/isISO31661Numeric.js @@ -0,0 +1,26 @@ +import assertString from './util/assertString'; + +// from https://en.wikipedia.org/wiki/ISO_3166-1_numeric +const validISO31661NumericCountriesCodes = new Set([ + '004', '008', '010', '012', '016', '020', '024', '028', '031', '032', '036', '040', '044', '048', '050', '051', + '052', '056', '060', '064', '068', '070', '072', '074', '076', '084', '086', '090', '092', '096', '100', '104', + '108', '112', '116', '120', '124', '132', '136', '140', '144', '148', '152', '156', '158', '162', '166', '170', + '174', '175', '178', '180', '184', '188', '191', '192', '196', '203', '204', '208', '212', '214', '218', '222', + '226', '231', '232', '233', '234', '238', '239', '242', '246', '248', '250', '254', '258', '260', '262', '266', + '268', '270', '275', '276', '288', '292', '296', '300', '304', '308', '312', '316', '320', '324', '328', '332', + '334', '336', '340', '344', '348', '352', '356', '360', '364', '368', '372', '376', '380', '384', '388', '392', + '398', '400', '404', '408', '410', '414', '417', '418', '422', '426', '428', '430', '434', '438', '440', '442', + '446', '450', '454', '458', '462', '466', '470', '474', '478', '480', '484', '492', '496', '498', '499', '500', + '504', '508', '512', '516', '520', '524', '528', '531', '533', '534', '535', '540', '548', '554', '558', '562', + '566', '570', '574', '578', '580', '581', '583', '584', '585', '586', '591', '598', '600', '604', '608', '612', + '616', '620', '624', '626', '630', '634', '638', '642', '643', '646', '652', '654', '659', '660', '662', '663', + '666', '670', '674', '678', '682', '686', '688', '690', '694', '702', '703', '704', '705', '706', '710', '716', + '724', '728', '729', '732', '740', '744', '748', '752', '756', '760', '762', '764', '768', '772', '776', '780', + '784', '788', '792', '795', '796', '798', '800', '804', '807', '818', '826', '831', '832', '833', '834', '840', + '850', '854', '858', '860', '862', '876', '882', '887', '894', +]); + +export default function isISO31661Numeric(str) { + assertString(str); + return validISO31661NumericCountriesCodes.has(str); +} diff --git a/src/lib/isISO4217.js b/src/lib/isISO4217.js index 0738614c9..bbca596a9 100644 --- a/src/lib/isISO4217.js +++ b/src/lib/isISO4217.js @@ -4,12 +4,12 @@ import assertString from './util/assertString'; const validISO4217CurrencyCodes = new Set([ 'AED', 'AFN', 'ALL', 'AMD', 'ANG', 'AOA', 'ARS', 'AUD', 'AWG', 'AZN', 'BAM', 'BBD', 'BDT', 'BGN', 'BHD', 'BIF', 'BMD', 'BND', 'BOB', 'BOV', 'BRL', 'BSD', 'BTN', 'BWP', 'BYN', 'BZD', - 'CAD', 'CDF', 'CHE', 'CHF', 'CHW', 'CLF', 'CLP', 'CNY', 'COP', 'COU', 'CRC', 'CUC', 'CUP', 'CVE', 'CZK', + 'CAD', 'CDF', 'CHE', 'CHF', 'CHW', 'CLF', 'CLP', 'CNY', 'COP', 'COU', 'CRC', 'CUP', 'CVE', 'CZK', 'DJF', 'DKK', 'DOP', 'DZD', 'EGP', 'ERN', 'ETB', 'EUR', 'FJD', 'FKP', 'GBP', 'GEL', 'GHS', 'GIP', 'GMD', 'GNF', 'GTQ', 'GYD', - 'HKD', 'HNL', 'HRK', 'HTG', 'HUF', + 'HKD', 'HNL', 'HTG', 'HUF', 'IDR', 'ILS', 'INR', 'IQD', 'IRR', 'ISK', 'JMD', 'JOD', 'JPY', 'KES', 'KGS', 'KHR', 'KMF', 'KPW', 'KRW', 'KWD', 'KYD', 'KZT', @@ -20,10 +20,10 @@ const validISO4217CurrencyCodes = new Set([ 'PAB', 'PEN', 'PGK', 'PHP', 'PKR', 'PLN', 'PYG', 'QAR', 'RON', 'RSD', 'RUB', 'RWF', - 'SAR', 'SBD', 'SCR', 'SDG', 'SEK', 'SGD', 'SHP', 'SLL', 'SOS', 'SRD', 'SSP', 'STN', 'SVC', 'SYP', 'SZL', + 'SAR', 'SBD', 'SCR', 'SDG', 'SEK', 'SGD', 'SHP', 'SLE', 'SLL', 'SOS', 'SRD', 'SSP', 'STN', 'SVC', 'SYP', 'SZL', 'THB', 'TJS', 'TMT', 'TND', 'TOP', 'TRY', 'TTD', 'TWD', 'TZS', 'UAH', 'UGX', 'USD', 'USN', 'UYI', 'UYU', 'UYW', 'UZS', - 'VES', 'VND', 'VUV', + 'VED', 'VES', 'VND', 'VUV', 'WST', 'XAF', 'XAG', 'XAU', 'XBA', 'XBB', 'XBC', 'XBD', 'XCD', 'XDR', 'XOF', 'XPD', 'XPF', 'XPT', 'XSU', 'XTS', 'XUA', 'XXX', 'YER', diff --git a/src/lib/isISO6346.js b/src/lib/isISO6346.js index 0cb657e7c..2c28c1123 100644 --- a/src/lib/isISO6346.js +++ b/src/lib/isISO6346.js @@ -27,7 +27,8 @@ export function isISO6346(str) { } else sum += str[i] * (2 ** i); } - const checkSumDigit = sum % 11; + let checkSumDigit = sum % 11; + if (checkSumDigit === 10) checkSumDigit = 0; return Number(str[str.length - 1]) === checkSumDigit; } diff --git a/src/lib/isIdentityCard.js b/src/lib/isIdentityCard.js index 4734b7bd9..060618fce 100644 --- a/src/lib/isIdentityCard.js +++ b/src/lib/isIdentityCard.js @@ -421,6 +421,16 @@ const validators = { return sum + (Number(number) * (9 - index)); }, 0); }, + PK: (str) => { + // Pakistani National Identity Number CNIC is 13 digits + const CNIC = /^[1-7][0-9]{4}-[0-9]{7}-[1-9]$/; + + // sanitize user input + const sanitized = str.trim(); + + // validate the data structure + return CNIC.test(sanitized); + }, }; export default function isIdentityCard(str, locale) { diff --git a/src/lib/isInt.js b/src/lib/isInt.js index 8047a6969..d5616089a 100644 --- a/src/lib/isInt.js +++ b/src/lib/isInt.js @@ -1,4 +1,5 @@ import assertString from './util/assertString'; +import isNullOrUndefined from './util/nullUndefinedCheck'; const int = /^(?:[-+]?(?:0|[1-9][0-9]*))$/; const intLeadingZeroes = /^[-+]?[0-9]+$/; @@ -9,16 +10,13 @@ export default function isInt(str, options) { // Get the regex to use for testing, based on whether // leading zeroes are allowed or not. - let regex = ( - options.hasOwnProperty('allow_leading_zeroes') && !options.allow_leading_zeroes ? - int : intLeadingZeroes - ); + const regex = options.allow_leading_zeroes === false ? int : intLeadingZeroes; // Check min/max/lt/gt - let minCheckPassed = (!options.hasOwnProperty('min') || str >= options.min); - let maxCheckPassed = (!options.hasOwnProperty('max') || str <= options.max); - let ltCheckPassed = (!options.hasOwnProperty('lt') || str < options.lt); - let gtCheckPassed = (!options.hasOwnProperty('gt') || str > options.gt); + let minCheckPassed = (!options.hasOwnProperty('min') || isNullOrUndefined(options.min) || str >= options.min); + let maxCheckPassed = (!options.hasOwnProperty('max') || isNullOrUndefined(options.max) || str <= options.max); + let ltCheckPassed = (!options.hasOwnProperty('lt') || isNullOrUndefined(options.lt) || str < options.lt); + let gtCheckPassed = (!options.hasOwnProperty('gt') || isNullOrUndefined(options.gt) || str > options.gt); return regex.test(str) && minCheckPassed && maxCheckPassed && ltCheckPassed && gtCheckPassed; } diff --git a/src/lib/isLength.js b/src/lib/isLength.js index 4ef8b83eb..4d5d52546 100644 --- a/src/lib/isLength.js +++ b/src/lib/isLength.js @@ -5,6 +5,7 @@ export default function isLength(str, options) { assertString(str); let min; let max; + if (typeof (options) === 'object') { min = options.min || 0; max = options.max; @@ -12,8 +13,15 @@ export default function isLength(str, options) { min = arguments[1] || 0; max = arguments[2]; } + const presentationSequences = str.match(/(\uFE0F|\uFE0E)/g) || []; const surrogatePairs = str.match(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g) || []; const len = str.length - presentationSequences.length - surrogatePairs.length; - return len >= min && (typeof max === 'undefined' || len <= max); + const isInsideRange = len >= min && (typeof max === 'undefined' || len <= max); + + if (isInsideRange && Array.isArray(options?.discreteLengths)) { + return options.discreteLengths.some(discreteLen => discreteLen === len); + } + + return isInsideRange; } diff --git a/src/lib/isLicensePlate.js b/src/lib/isLicensePlate.js index 48f8ebe99..bd146be91 100644 --- a/src/lib/isLicensePlate.js +++ b/src/lib/isLicensePlate.js @@ -7,6 +7,7 @@ const validators = { /^((A|AA|AB|AC|AE|AH|AK|AM|AN|AÖ|AP|AS|AT|AU|AW|AZ|B|BA|BB|BC|BE|BF|BH|BI|BK|BL|BM|BN|BO|BÖ|BS|BT|BZ|C|CA|CB|CE|CO|CR|CW|D|DA|DD|DE|DH|DI|DL|DM|DN|DO|DU|DW|DZ|E|EA|EB|ED|EE|EF|EG|EH|EI|EL|EM|EN|ER|ES|EU|EW|F|FB|FD|FF|FG|FI|FL|FN|FO|FR|FS|FT|FÜ|FW|FZ|G|GA|GC|GD|GE|GF|GG|GI|GK|GL|GM|GN|GÖ|GP|GR|GS|GT|GÜ|GV|GW|GZ|H|HA|HB|HC|HD|HE|HF|HG|HH|HI|HK|HL|HM|HN|HO|HP|HR|HS|HU|HV|HX|HY|HZ|IK|IL|IN|IZ|J|JE|JL|K|KA|KB|KC|KE|KF|KG|KH|KI|KK|KL|KM|KN|KO|KR|KS|KT|KU|KW|KY|L|LA|LB|LC|LD|LF|LG|LH|LI|LL|LM|LN|LÖ|LP|LR|LU|M|MA|MB|MC|MD|ME|MG|MH|MI|MK|ML|MM|MN|MO|MQ|MR|MS|MÜ|MW|MY|MZ|N|NB|ND|NE|NF|NH|NI|NK|NM|NÖ|NP|NR|NT|NU|NW|NY|NZ|OA|OB|OC|OD|OE|OF|OG|OH|OK|OL|OP|OS|OZ|P|PA|PB|PE|PF|PI|PL|PM|PN|PR|PS|PW|PZ|R|RA|RC|RD|RE|RG|RH|RI|RL|RM|RN|RO|RP|RS|RT|RU|RV|RW|RZ|S|SB|SC|SE|SG|SI|SK|SL|SM|SN|SO|SP|SR|ST|SU|SW|SY|SZ|TE|TF|TG|TO|TP|TR|TS|TT|TÜ|ÜB|UE|UH|UL|UM|UN|V|VB|VG|VK|VR|VS|W|WA|WB|WE|WF|WI|WK|WL|WM|WN|WO|WR|WS|WT|WÜ|WW|WZ|Z|ZE|ZI|ZP|ZR|ZW|ZZ)[- ]?[A-Z]{1,2}[- ]?\d{1,4}|(ABG|ABI|AIB|AIC|ALF|ALZ|ANA|ANG|ANK|APD|ARN|ART|ASL|ASZ|AUR|AZE|BAD|BAR|BBG|BCH|BED|BER|BGD|BGL|BID|BIN|BIR|BIT|BIW|BKS|BLB|BLK|BNA|BOG|BOH|BOR|BOT|BRA|BRB|BRG|BRK|BRL|BRV|BSB|BSK|BTF|BÜD|BUL|BÜR|BÜS|BÜZ|CAS|CHA|CLP|CLZ|COC|COE|CUX|DAH|DAN|DAU|DBR|DEG|DEL|DGF|DIL|DIN|DIZ|DKB|DLG|DON|DUD|DÜW|EBE|EBN|EBS|ECK|EIC|EIL|EIN|EIS|EMD|EMS|ERB|ERH|ERK|ERZ|ESB|ESW|FDB|FDS|FEU|FFB|FKB|FLÖ|FOR|FRG|FRI|FRW|FTL|FÜS|GAN|GAP|GDB|GEL|GEO|GER|GHA|GHC|GLA|GMN|GNT|GOA|GOH|GRA|GRH|GRI|GRM|GRZ|GTH|GUB|GUN|GVM|HAB|HAL|HAM|HAS|HBN|HBS|HCH|HDH|HDL|HEB|HEF|HEI|HER|HET|HGN|HGW|HHM|HIG|HIP|HMÜ|HOG|HOH|HOL|HOM|HOR|HÖS|HOT|HRO|HSK|HST|HVL|HWI|IGB|ILL|JÜL|KEH|KEL|KEM|KIB|KLE|KLZ|KÖN|KÖT|KÖZ|KRU|KÜN|KUS|KYF|LAN|LAU|LBS|LBZ|LDK|LDS|LEO|LER|LEV|LIB|LIF|LIP|LÖB|LOS|LRO|LSZ|LÜN|LUP|LWL|MAB|MAI|MAK|MAL|MED|MEG|MEI|MEK|MEL|MER|MET|MGH|MGN|MHL|MIL|MKK|MOD|MOL|MON|MOS|MSE|MSH|MSP|MST|MTK|MTL|MÜB|MÜR|MYK|MZG|NAB|NAI|NAU|NDH|NEA|NEB|NEC|NEN|NES|NEW|NMB|NMS|NOH|NOL|NOM|NOR|NVP|NWM|OAL|OBB|OBG|OCH|OHA|ÖHR|OHV|OHZ|OPR|OSL|OVI|OVL|OVP|PAF|PAN|PAR|PCH|PEG|PIR|PLÖ|PRÜ|QFT|QLB|RDG|REG|REH|REI|RID|RIE|ROD|ROF|ROK|ROL|ROS|ROT|ROW|RSL|RÜD|RÜG|SAB|SAD|SAN|SAW|SBG|SBK|SCZ|SDH|SDL|SDT|SEB|SEE|SEF|SEL|SFB|SFT|SGH|SHA|SHG|SHK|SHL|SIG|SIM|SLE|SLF|SLK|SLN|SLS|SLÜ|SLZ|SMÜ|SOB|SOG|SOK|SÖM|SON|SPB|SPN|SRB|SRO|STA|STB|STD|STE|STL|SUL|SÜW|SWA|SZB|TBB|TDO|TET|TIR|TÖL|TUT|UEM|UER|UFF|USI|VAI|VEC|VER|VIB|VIE|VIT|VOH|WAF|WAK|WAN|WAR|WAT|WBS|WDA|WEL|WEN|WER|WES|WHV|WIL|WIS|WIT|WIZ|WLG|WMS|WND|WOB|WOH|WOL|WOR|WOS|WRN|WSF|WST|WSW|WTL|WTM|WUG|WÜM|WUN|WUR|WZL|ZEL|ZIG)[- ]?(([A-Z][- ]?\d{1,4})|([A-Z]{2}[- ]?\d{1,3})))[- ]?(E|H)?$/.test(str), 'de-LI': str => /^FL[- ]?\d{1,5}[UZ]?$/.test(str), 'en-IN': str => /^[A-Z]{2}[ -]?[0-9]{1,2}(?:[ -]?[A-Z])(?:[ -]?[A-Z]*)?[ -]?[0-9]{4}$/.test(str), + 'en-SG': str => /^[A-Z]{3}[ -]?[\d]{4}[ -]?[A-Z]{1}$/.test(str), 'es-AR': str => /^(([A-Z]{2} ?[0-9]{3} ?[A-Z]{2})|([A-Z]{3} ?[0-9]{3}))$/.test(str), 'fi-FI': str => /^(?=.{4,7})(([A-Z]{1,3}|[0-9]{1,3})[\s-]?([A-Z]{1,3}|[0-9]{1,5}))$/.test(str), 'hu-HU': str => /^((((?!AAA)(([A-NPRSTVZWXY]{1})([A-PR-Z]{1})([A-HJ-NPR-Z]))|(A[ABC]I)|A[ABC]O|A[A-W]Q|BPI|BPO|UCO|UDO|XAO)-(?!000)\d{3})|(M\d{6})|((CK|DT|CD|HC|H[ABEFIKLMNPRSTVX]|MA|OT|R[A-Z]) \d{2}-\d{2})|(CD \d{3}-\d{3})|(C-(C|X) \d{4})|(X-(A|B|C) \d{4})|(([EPVZ]-\d{5}))|(S A[A-Z]{2} \d{2})|(SP \d{2}-\d{2}))$/.test(str), @@ -18,6 +19,7 @@ const validators = { /^[A-Z]{2}[- ]?((\d{3}[- ]?(([A-Z]{2})|T))|(R[- ]?\d{3}))$/.test(str), 'sv-SE': str => /^[A-HJ-PR-UW-Z]{3} ?[\d]{2}[A-HJ-PR-UW-Z1-9]$|(^[A-ZÅÄÖ ]{2,7}$)/.test(str.trim()), + 'en-PK': str => /(^[A-Z]{2}((\s|-){0,1})[0-9]{3,4}((\s|-)[0-9]{2}){0,1}$)|(^[A-Z]{3}((\s|-){0,1})[0-9]{3,4}((\s|-)[0-9]{2}){0,1}$)|(^[A-Z]{4}((\s|-){0,1})[0-9]{3,4}((\s|-)[0-9]{2}){0,1}$)|(^[A-Z]((\s|-){0,1})[0-9]{4}((\s|-)[0-9]{2}){0,1}$)/.test(str.trim()), }; export default function isLicensePlate(str, locale) { diff --git a/src/lib/isMailtoURI.js b/src/lib/isMailtoURI.js index 0dd95b6a9..67748a553 100644 --- a/src/lib/isMailtoURI.js +++ b/src/lib/isMailtoURI.js @@ -41,7 +41,7 @@ export default function isMailtoURI(url, options) { return false; } - const [to = '', queryString = ''] = url.replace('mailto:', '').split('?'); + const [to, queryString = ''] = url.replace('mailto:', '').split('?'); if (!to && !queryString) { return true; diff --git a/src/lib/isMimeType.js b/src/lib/isMimeType.js index 4081117af..820fa4dc2 100644 --- a/src/lib/isMimeType.js +++ b/src/lib/isMimeType.js @@ -4,18 +4,18 @@ import assertString from './util/assertString'; Checks if the provided string matches to a correct Media type format (MIME type) This function only checks is the string format follows the - etablished rules by the according RFC specifications. + established rules by the according RFC specifications. This function supports 'charset' in textual media types (https://tools.ietf.org/html/rfc6657). This function does not check against all the media types listed by the IANA (https://www.iana.org/assignments/media-types/media-types.xhtml) because of lightness purposes : it would require to include - all these MIME types in this librairy, which would weigh it + all these MIME types in this library, which would weigh it significantly. This kind of effort maybe is not worth for the use that - this function has in this entire librairy. + this function has in this entire library. - More informations in the RFC specifications : + More information in the RFC specifications : - https://tools.ietf.org/html/rfc2045 - https://tools.ietf.org/html/rfc2046 - https://tools.ietf.org/html/rfc7231#section-3.1.1.1 diff --git a/src/lib/isMobilePhone.js b/src/lib/isMobilePhone.js index 7c9b420e9..ec1483d65 100644 --- a/src/lib/isMobilePhone.js +++ b/src/lib/isMobilePhone.js @@ -2,7 +2,7 @@ import assertString from './util/assertString'; /* eslint-disable max-len */ const phones = { - 'am-AM': /^(\+?374|0)((10|[9|7][0-9])\d{6}$|[2-4]\d{7}$)/, + 'am-AM': /^(\+?374|0)(33|4[134]|55|77|88|9[13-689])\d{6}$/, 'ar-AE': /^((\+?971)|0)?5[024568]\d{7}$/, 'ar-BH': /^(\+?973)?(3|6)\d{7}$/, 'ar-DZ': /^(\+?213|0)(5|6|7)\d{8}$/, @@ -13,7 +13,7 @@ const phones = { 'ar-KW': /^(\+?965)([569]\d{7}|41\d{6})$/, 'ar-LY': /^((\+?218)|0)?(9[1-6]\d{7}|[1-8]\d{7,9})$/, 'ar-MA': /^(?:(?:\+|00)212|0)[5-7]\d{8}$/, - 'ar-OM': /^((\+|00)968)?(9[1-9])\d{6}$/, + 'ar-OM': /^((\+|00)968)?([79][1-9])\d{6}$/, 'ar-PS': /^(\+?970|0)5[6|9](\d{7})$/, 'ar-SA': /^(!?(\+?966)|0)?5\d{8}$/, 'ar-SD': /^((\+?249)|0)?(9[012369]|1[012])\d{7}$/, @@ -33,15 +33,15 @@ const phones = { 'de-LU': /^(\+352)?((6\d1)\d{6})$/, 'dv-MV': /^(\+?960)?(7[2-9]|9[1-9])\d{5}$/, 'el-GR': /^(\+?30|0)?6(8[5-9]|9(?![26])[0-9])\d{7}$/, - 'el-CY': /^(\+?357?)?(9(9|6)\d{6})$/, + 'el-CY': /^(\+?357?)?(9(9|7|6|5|4)\d{6})$/, 'en-AI': /^(\+?1|0)264(?:2(35|92)|4(?:6[1-2]|76|97)|5(?:3[6-9]|8[1-4])|7(?:2(4|9)|72))\d{4}$/, 'en-AU': /^(\+?61|0)4\d{8}$/, 'en-AG': /^(?:\+1|1)268(?:464|7(?:1[3-9]|[28]\d|3[0246]|64|7[0-689]))\d{4}$/, 'en-BM': /^(\+?1)?441(((3|7)\d{6}$)|(5[0-3][0-9]\d{4}$)|(59\d{5}$))/, 'en-BS': /^(\+?1[-\s]?|0)?\(?242\)?[-\s]?\d{3}[-\s]?\d{4}$/, - 'en-GB': /^(\+?44|0)7\d{9}$/, + 'en-GB': /^(\+?44|0)7[1-9]\d{8}$/, 'en-GG': /^(\+?44|0)1481\d{6}$/, - 'en-GH': /^(\+233|0)(20|50|24|54|27|57|26|56|23|28|55|59)\d{7}$/, + 'en-GH': /^(\+233|0)(20|50|24|54|27|57|26|56|23|53|28|55|59)\d{7}$/, 'en-GY': /^(\+592|0)6\d{6}$/, 'en-HK': /^(\+?852[-\s]?)?[456789]\d{3}[-\s]?\d{4}$/, 'en-MO': /^(\+?853[-\s]?)?[6]\d{3}[-\s]?\d{4}$/, @@ -70,7 +70,7 @@ const phones = { 'en-UG': /^(\+?256|0)?[7]\d{8}$/, 'en-US': /^((\+1|1)?( |-)?)?(\([2-9][0-9]{2}\)|[2-9][0-9]{2})( |-)?([2-9][0-9]{2}( |-)?[0-9]{4})$/, 'en-ZA': /^(\+?27|0)\d{9}$/, - 'en-ZM': /^(\+?26)?09[567]\d{7}$/, + 'en-ZM': /^(\+?26)?0[79][567]\d{7}$/, 'en-ZW': /^(\+263)[0-9]{9}$/, 'en-BW': /^(\+?267)?(7[1-8]{1})\d{6}$/, 'es-AR': /^\+?549(11|[2368]\d)\d{8}$/, @@ -83,6 +83,7 @@ const phones = { 'es-HN': /^(\+?504)?[9|8|3|2]\d{7}$/, 'es-EC': /^(\+?593|0)([2-7]|9[2-9])\d{7}$/, 'es-ES': /^(\+?34)?[6|7]\d{8}$/, + 'es-GT': /^(\+?502)?[2|6|7]\d{7}$/, 'es-PE': /^(\+?51)?9\d{8}$/, 'es-MX': /^(\+?52)?(1|01)?\d{10,11}$/, 'es-NI': /^(\+?505)\d{7,8}$/, @@ -118,7 +119,7 @@ const phones = { 'kk-KZ': /^(\+?7|8)?7\d{9}$/, 'kl-GL': /^(\+?299)?\s?\d{2}\s?\d{2}\s?\d{2}$/, 'ko-KR': /^((\+?82)[ \-]?)?0?1([0|1|6|7|8|9]{1})[ \-]?\d{3,4}[ \-]?\d{4}$/, - 'ky-KG': /^(\+?7\s?\+?7|0)\s?\d{2}\s?\d{3}\s?\d{4}$/, + 'ky-KG': /^(\+996\s?)?(22[0-9]|50[0-9]|55[0-9]|70[0-9]|75[0-9]|77[0-9]|880|990|995|996|997|998)\s?\d{3}\s?\d{3}$/, 'lt-LT': /^(\+370|8)\d{8}$/, 'lv-LV': /^(\+?371)2\d{7}$/, 'mg-MG': /^((\+?261|0)(2|3)\d)?\d{7}$/, @@ -135,7 +136,7 @@ const phones = { 'pl-PL': /^(\+?48)? ?([5-8]\d|45) ?\d{3} ?\d{2} ?\d{2}$/, 'pt-BR': /^((\+?55\ ?[1-9]{2}\ ?)|(\+?55\ ?\([1-9]{2}\)\ ?)|(0[1-9]{2}\ ?)|(\([1-9]{2}\)\ ?)|([1-9]{2}\ ?))((\d{4}\-?\d{4})|(9[1-9]{1}\d{3}\-?\d{4}))$/, 'pt-PT': /^(\+?351)?9[1236]\d{7}$/, - 'pt-AO': /^(\+244)\d{9}$/, + 'pt-AO': /^(\+?244)?9\d{8}$/, 'ro-MD': /^(\+?373|0)((6(0|1|2|6|7|8|9))|(7(6|7|8|9)))\d{6}$/, 'ro-RO': /^(\+?40|0)\s?7\d{2}(\/|\s|\.|-)?\d{3}(\s|\.|-)?\d{3}$/, 'ru-RU': /^(\+?7|8)?9\d{9}$/, @@ -143,14 +144,14 @@ const phones = { 'sl-SI': /^(\+386\s?|0)(\d{1}\s?\d{3}\s?\d{2}\s?\d{2}|\d{2}\s?\d{3}\s?\d{3})$/, 'sk-SK': /^(\+?421)? ?[1-9][0-9]{2} ?[0-9]{3} ?[0-9]{3}$/, 'so-SO': /^(\+?252|0)((6[0-9])\d{7}|(7[1-9])\d{7})$/, - 'sq-AL': /^(\+355|0)6[789]\d{6}$/, + 'sq-AL': /^(\+355|0)6[2-9]\d{7}$/, 'sr-RS': /^(\+3816|06)[- \d]{5,9}$/, 'sv-SE': /^(\+?46|0)[\s\-]?7[\s\-]?[02369]([\s\-]?\d){7}$/, 'tg-TJ': /^(\+?992)?[5][5]\d{7}$/, 'th-TH': /^(\+66|66|0)\d{9}$/, 'tr-TR': /^(\+?90|0)?5\d{9}$/, 'tk-TM': /^(\+993|993|8)\d{8}$/, - 'uk-UA': /^(\+?38|8)?0\d{9}$/, + 'uk-UA': /^(\+?38)?0(50|6[36-8]|7[357]|9[1-9])\d{7}$/, 'uz-UZ': /^(\+?998)?(6[125-79]|7[1-69]|88|9\d)\d{7}$/, 'vi-VN': /^((\+?84)|0)((3([2-9]))|(5([25689]))|(7([0|6-9]))|(8([1-9]))|(9([0-9])))([0-9]{7})$/, 'zh-CN': /^((\+|00)86)?(1[3-9]|9[28])\d{9}$/, @@ -159,6 +160,7 @@ const phones = { 'ar-YE': /^(((\+|00)9677|0?7)[0137]\d{7}|((\+|00)967|0)[1-7]\d{6})$/, 'ar-EH': /^(\+?212|0)[\s\-]?(5288|5289)[\s\-]?\d{5}$/, 'fa-AF': /^(\+93|0)?(2{1}[0-8]{1}|[3-5]{1}[0-4]{1})(\d{7})$/, + 'mk-MK': /^(\+?389|0)?((?:2[2-9]\d{6}|(?:3[1-4]|4[2-8])\d{6}|500\d{5}|5[2-9]\d{6}|7[0-9][2-9]\d{5}|8[1-9]\d{6}|800\d{5}|8009\d{4}))$/, }; /* eslint-enable max-len */ diff --git a/src/lib/isPassportNumber.js b/src/lib/isPassportNumber.js index 4763d6566..33481e8c3 100644 --- a/src/lib/isPassportNumber.js +++ b/src/lib/isPassportNumber.js @@ -11,12 +11,12 @@ const passportRegexByCountryCode = { AR: /^[A-Z]{3}\d{6}$/, // ARGENTINA AT: /^[A-Z]\d{7}$/, // AUSTRIA AU: /^[A-Z]\d{7}$/, // AUSTRALIA - AZ: /^[A-Z]{2,3}\d{7,8}$/, // AZERBAIJAN + AZ: /^[A-Z]{1}\d{8}$/, // AZERBAIJAN BE: /^[A-Z]{2}\d{6}$/, // BELGIUM BG: /^\d{9}$/, // BULGARIA BR: /^[A-Z]{2}\d{6}$/, // BRAZIL BY: /^[A-Z]{2}\d{7}$/, // BELARUS - CA: /^[A-Z]{2}\d{6}$/, // CANADA + CA: /^[A-Z]{2}\d{6}$|^[A-Z]\d{6}[A-Z]{2}$/, // CANADA CH: /^[A-Z]\d{7}$/, // SWITZERLAND CN: /^G\d{8}$|^E(?![IO])[A-Z0-9]\d{7}$/, // CHINA [G=Ordinary, E=Electronic] followed by 8-digits, or E followed by any UPPERCASE letter (except I and O) followed by 7 digits CY: /^[A-Z](\d{6}|\d{8})$/, // CYPRUS @@ -69,6 +69,8 @@ const passportRegexByCountryCode = { ZA: /^[TAMD]\d{8}$/, // SOUTH AFRICA }; +export const locales = Object.keys(passportRegexByCountryCode); + /** * Check if str is a valid passport number * relative to provided ISO Country Code. diff --git a/src/lib/isPort.js b/src/lib/isPort.js index 0b316b78c..0a9ddce1d 100644 --- a/src/lib/isPort.js +++ b/src/lib/isPort.js @@ -1,5 +1,5 @@ import isInt from './isInt'; export default function isPort(str) { - return isInt(str, { min: 0, max: 65535 }); + return isInt(str, { allow_leading_zeroes: false, min: 0, max: 65535 }); } diff --git a/src/lib/isPostalCode.js b/src/lib/isPostalCode.js index e6213914f..01ae3fc07 100644 --- a/src/lib/isPostalCode.js +++ b/src/lib/isPostalCode.js @@ -14,11 +14,12 @@ const patterns = { BA: /^([7-8]\d{4}$)/, BE: fourDigit, BG: fourDigit, - BR: /^\d{5}-\d{3}$/, + BR: /^\d{5}-?\d{3}$/, BY: /^2[1-4]\d{4}$/, CA: /^[ABCEGHJKLMNPRSTVXY]\d[ABCEGHJ-NPRSTV-Z][\s\-]?\d[ABCEGHJ-NPRSTV-Z]\d$/i, CH: fourDigit, CN: /^(0[1-7]|1[012356]|2[0-7]|3[0-6]|4[0-7]|5[1-7]|6[1-7]|7[1-5]|8[1345]|9[09])\d{4}$/, + CO: /^(05|08|11|13|15|17|18|19|20|23|25|27|41|44|47|50|52|54|63|66|68|70|73|76|81|85|86|88|91|94|95|97|99)(\d{4})$/, CZ: /^\d{3}\s?\d{2}$/, DE: fiveDigit, DK: fourDigit, @@ -27,7 +28,7 @@ const patterns = { EE: fiveDigit, ES: /^(5[0-2]{1}|[0-4]{1}\d{1})\d{3}$/, FI: fiveDigit, - FR: /^\d{2}\s?\d{3}$/, + FR: /^(?:(?:0[1-9]|[1-8]\d|9[0-5])\d{3}|97[1-46]\d{2})$/, GB: /^(gir\s?0aa|[a-z]{1,2}\d[\da-z]?\s?(\d[a-z]{2})?)$/i, GR: /^\d{3}\s?\d{2}$/, HR: /^([1-5]\d{4}$)/, @@ -52,7 +53,7 @@ const patterns = { MX: fiveDigit, MT: /^[A-Za-z]{3}\s{0,1}\d{4}$/, MY: fiveDigit, - NL: /^\d{4}\s?[a-z]{2}$/i, + NL: /^[1-9]\d{3}\s?(?!sa|sd|ss)[a-z]{2}$/i, NO: fourDigit, NP: /^(10|21|22|32|33|34|44|45|56|57)\d{3}$|^(977)$/i, NZ: fourDigit, diff --git a/src/lib/isRgbColor.js b/src/lib/isRgbColor.js index 9458522ab..6e2866243 100644 --- a/src/lib/isRgbColor.js +++ b/src/lib/isRgbColor.js @@ -1,12 +1,35 @@ +/* eslint-disable prefer-rest-params */ import assertString from './util/assertString'; const rgbColor = /^rgb\((([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5]),){2}([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\)$/; -const rgbaColor = /^rgba\((([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5]),){3}(0?\.\d|1(\.0)?|0(\.0)?)\)$/; +const rgbaColor = /^rgba\((([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5]),){3}(0?\.\d\d?|1(\.0)?|0(\.0)?)\)$/; const rgbColorPercent = /^rgb\((([0-9]%|[1-9][0-9]%|100%),){2}([0-9]%|[1-9][0-9]%|100%)\)$/; -const rgbaColorPercent = /^rgba\((([0-9]%|[1-9][0-9]%|100%),){3}(0?\.\d|1(\.0)?|0(\.0)?)\)$/; +const rgbaColorPercent = /^rgba\((([0-9]%|[1-9][0-9]%|100%),){3}(0?\.\d\d?|1(\.0)?|0(\.0)?)\)$/; +const startsWithRgb = /^rgba?/; -export default function isRgbColor(str, includePercentValues = true) { +export default function isRgbColor(str, options) { assertString(str); + // default options to true for percent and false for spaces + let allowSpaces = false; + let includePercentValues = true; + if (typeof options !== 'object') { + if (arguments.length >= 2) { + includePercentValues = arguments[1]; + } + } else { + allowSpaces = options.allowSpaces !== undefined ? options.allowSpaces : allowSpaces; + includePercentValues = options.includePercentValues !== undefined ? + options.includePercentValues : includePercentValues; + } + + if (allowSpaces) { + // make sure it starts with continous rgba? without spaces before stripping + if (!startsWithRgb.test(str)) { + return false; + } + // strip all whitespace + str = str.replace(/\s/g, ''); + } if (!includePercentValues) { return rgbColor.test(str) || rgbaColor.test(str); diff --git a/src/lib/isStrongPassword.js b/src/lib/isStrongPassword.js index 5db901fa3..8fe9223b7 100644 --- a/src/lib/isStrongPassword.js +++ b/src/lib/isStrongPassword.js @@ -4,7 +4,7 @@ import assertString from './util/assertString'; const upperCaseRegex = /^[A-Z]$/; const lowerCaseRegex = /^[a-z]$/; const numberRegex = /^[0-9]$/; -const symbolRegex = /^[-#!$@£%^&*()_+|~=`{}\[\]:";'<>?,.\/ ]$/; +const symbolRegex = /^[-#!$@£%^&*()_+|~=`{}\[\]:";'<>?,.\/\\ ]$/; const defaultOptions = { minLength: 8, diff --git a/src/lib/isTaxID.js b/src/lib/isTaxID.js index b82156ed1..5e5f8cb5b 100644 --- a/src/lib/isTaxID.js +++ b/src/lib/isTaxID.js @@ -174,24 +174,24 @@ function deDeCheck(tin) { const digits = tin.split('').map(a => parseInt(a, 10)); // Fill array with strings of number positions - let occurences = []; + let occurrences = []; for (let i = 0; i < digits.length - 1; i++) { - occurences.push(''); + occurrences.push(''); for (let j = 0; j < digits.length - 1; j++) { if (digits[i] === digits[j]) { - occurences[i] += j; + occurrences[i] += j; } } } - // Remove digits with one occurence and test for only one duplicate/triplicate - occurences = occurences.filter(a => a.length > 1); - if (occurences.length !== 2 && occurences.length !== 3) { return false; } + // Remove digits with one occurrence and test for only one duplicate/triplicate + occurrences = occurrences.filter(a => a.length > 1); + if (occurrences.length !== 2 && occurrences.length !== 3) { return false; } // In case of triplicate value only two digits are allowed next to each other - if (occurences[0].length === 3) { - const trip_locations = occurences[0].split('').map(a => parseInt(a, 10)); - let recurrent = 0; // Amount of neighbour occurences + if (occurrences[0].length === 3) { + const trip_locations = occurrences[0].split('').map(a => parseInt(a, 10)); + let recurrent = 0; // Amount of neighbor occurrences for (let i = 0; i < trip_locations.length - 1; i++) { if (trip_locations[i] + 1 === trip_locations[i + 1]) { recurrent += 1; @@ -621,10 +621,10 @@ function huHuCheck(tin) { * and X characters after vowels may only be followed by other X characters. */ function itItNameCheck(name) { - // true at the first occurence of a vowel + // true at the first occurrence of a vowel let vowelflag = false; - // true at the first occurence of an X AFTER vowel + // true at the first occurrence of an X AFTER vowel // (to properly handle last names with X as consonant) let xflag = false; @@ -890,7 +890,7 @@ function plPlCheck(tin) { const date = `${full_year}/${month}/${tin.slice(4, 6)}`; if (!isDate(date, 'YYYY/MM/DD')) { return false; } - // Calculate last digit by mulitplying with odd one-digit numbers except 5 + // Calculate last digit by multiplying with odd one-digit numbers except 5 let checksum = 0; let multiplier = 1; for (let i = 0; i < tin.length - 1; i++) { @@ -1141,6 +1141,21 @@ function svSeCheck(tin) { return algorithms.luhnCheck(tin.replace(/\W/, '')); } +/** + * uk-UA validation function + * Verify TIN validity by calculating check (last) digit (variant of MOD 11) + */ +function ukUaCheck(tin) { + // Calculate check digit + const digits = tin.split('').map(a => parseInt(a, 10)); + const multipliers = [-1, 5, 7, 9, 4, 6, 10, 5, 7]; + let checksum = 0; + for (let i = 0; i < multipliers.length; i++) { + checksum += digits[i] * multipliers[i]; + } + return checksum % 11 === 10 ? digits[9] === 0 : digits[9] === checksum % 11; +} + // Locale lookup objects /* @@ -1181,6 +1196,7 @@ const taxIdFormat = { 'sk-SK': /^\d{6}\/{0,1}\d{3,4}$/, 'sl-SI': /^[1-9]\d{7}$/, 'sv-SE': /^(\d{6}[-+]{0,1}\d{4}|(18|19|20)\d{6}[-+]{0,1}\d{4})$/, + 'uk-UA': /^\d{10}$/, }; // taxIdFormat locale aliases taxIdFormat['lb-LU'] = taxIdFormat['fr-LU']; @@ -1220,6 +1236,7 @@ const taxIdCheck = { 'sk-SK': skSkCheck, 'sl-SI': slSiCheck, 'sv-SE': svSeCheck, + 'uk-UA': ukUaCheck, }; // taxIdCheck locale aliases taxIdCheck['lb-LU'] = taxIdCheck['fr-LU']; diff --git a/src/lib/isTime.js b/src/lib/isTime.js index 076bbfa34..3169864c2 100644 --- a/src/lib/isTime.js +++ b/src/lib/isTime.js @@ -9,10 +9,12 @@ const formats = { hour24: { default: /^([01]?[0-9]|2[0-3]):([0-5][0-9])$/, withSeconds: /^([01]?[0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])$/, + withOptionalSeconds: /^([01]?[0-9]|2[0-3]):([0-5][0-9])(?::([0-5][0-9]))?$/, }, hour12: { default: /^(0?[1-9]|1[0-2]):([0-5][0-9]) (A|P)M$/, withSeconds: /^(0?[1-9]|1[0-2]):([0-5][0-9]):([0-5][0-9]) (A|P)M$/, + withOptionalSeconds: /^(0?[1-9]|1[0-2]):([0-5][0-9])(?::([0-5][0-9]))? (A|P)M$/, }, }; diff --git a/src/lib/isULID.js b/src/lib/isULID.js new file mode 100644 index 000000000..2ace6f471 --- /dev/null +++ b/src/lib/isULID.js @@ -0,0 +1,6 @@ +import assertString from './util/assertString'; + +export default function isULID(str) { + assertString(str); + return /^[0-7][0-9A-HJKMNP-TV-Z]{25}$/i.test(str); +} diff --git a/src/lib/isURL.js b/src/lib/isURL.js index 3d2b1df3e..9bfafbf0c 100644 --- a/src/lib/isURL.js +++ b/src/lib/isURL.js @@ -1,4 +1,5 @@ import assertString from './util/assertString'; +import checkHost from './util/checkHost'; import isFQDN from './isFQDN'; import isIP from './isIP'; @@ -13,8 +14,10 @@ protocols - valid protocols can be modified with this option require_host - if set as false isURL will not check if host is present in the URL require_port - if set as true isURL will check if port is present in the URL allow_protocol_relative_urls - if set as true protocol relative URLs will be allowed -validate_length - if set as false isURL will skip string length validation (IE maximum is 2083) - +validate_length - if set as false isURL will skip string length validation + max_allowed_length will be ignored if this is set as false +max_allowed_length - if set isURL will not allow URLs longer than max_allowed_length + default is 2084 that IE maximum URL length */ @@ -31,24 +34,11 @@ const default_url_options = { allow_fragments: true, allow_query_components: true, validate_length: true, + max_allowed_length: 2084, }; const wrapped_ipv6 = /^\[([^\]]+)\](?::([0-9]+))?$/; -function isRegExp(obj) { - return Object.prototype.toString.call(obj) === '[object RegExp]'; -} - -function checkHost(host, matches) { - for (let i = 0; i < matches.length; i++) { - let match = matches[i]; - if (host === match || (isRegExp(match) && match.test(host))) { - return true; - } - } - return false; -} - export default function isURL(url, options) { assertString(url); if (!url || /[\s<>]/.test(url)) { @@ -59,7 +49,7 @@ export default function isURL(url, options) { } options = merge(options, default_url_options); - if (options.validate_length && url.length >= 2083) { + if (options.validate_length && url.length > options.max_allowed_length) { return false; } diff --git a/src/lib/isUUID.js b/src/lib/isUUID.js index c026ca78c..786af002e 100644 --- a/src/lib/isUUID.js +++ b/src/lib/isUUID.js @@ -1,16 +1,28 @@ import assertString from './util/assertString'; const uuid = { - 1: /^[0-9A-F]{8}-[0-9A-F]{4}-1[0-9A-F]{3}-[0-9A-F]{4}-[0-9A-F]{12}$/i, - 2: /^[0-9A-F]{8}-[0-9A-F]{4}-2[0-9A-F]{3}-[0-9A-F]{4}-[0-9A-F]{12}$/i, - 3: /^[0-9A-F]{8}-[0-9A-F]{4}-3[0-9A-F]{3}-[0-9A-F]{4}-[0-9A-F]{12}$/i, + 1: /^[0-9A-F]{8}-[0-9A-F]{4}-1[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i, + 2: /^[0-9A-F]{8}-[0-9A-F]{4}-2[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i, + 3: /^[0-9A-F]{8}-[0-9A-F]{4}-3[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i, 4: /^[0-9A-F]{8}-[0-9A-F]{4}-4[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i, 5: /^[0-9A-F]{8}-[0-9A-F]{4}-5[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i, - all: /^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i, + 6: /^[0-9A-F]{8}-[0-9A-F]{4}-6[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i, + 7: /^[0-9A-F]{8}-[0-9A-F]{4}-7[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i, + 8: /^[0-9A-F]{8}-[0-9A-F]{4}-8[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i, + + nil: /^00000000-0000-0000-0000-000000000000$/i, + max: /^ffffffff-ffff-ffff-ffff-ffffffffffff$/i, + + // From https://github.com/uuidjs/uuid/blob/main/src/regex.js + all: /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i, }; export default function isUUID(str, version) { assertString(str); - const pattern = uuid[![undefined, null].includes(version) ? version : 'all']; - return !!pattern && pattern.test(str); + + if (version === undefined || version === null) { + version = 'all'; + } + + return version in uuid ? uuid[version].test(str) : false; } diff --git a/src/lib/isVAT.js b/src/lib/isVAT.js index ece7d8560..50fcf52e0 100644 --- a/src/lib/isVAT.js +++ b/src/lib/isVAT.js @@ -1,6 +1,22 @@ import assertString from './util/assertString'; import * as algorithms from './util/algorithms'; +const AU = (str) => { + const match = str.match(/^(AU)?(\d{11})$/); + if (!match) { + return false; + } + // @see {@link https://abr.business.gov.au/Help/AbnFormat} + const weights = [10, 1, 3, 5, 7, 9, 11, 13, 15, 17, 19]; + str = str.replace(/^AU/, ''); + const ABN = (parseInt(str.slice(0, 1), 10) - 1).toString() + str.slice(1); + let total = 0; + for (let i = 0; i < 11; i++) { + total += weights[i] * ABN.charAt(i); + } + return (total !== 0 && total % 89 === 0); +}; + const CH = (str) => { // @see {@link https://www.ech.ch/de/ech/ech-0097/5.2.0} const hasValidCheckNumber = (digits) => { @@ -68,14 +84,14 @@ export const vatMatchers = { */ AL: str => /^(AL)?\w{9}[A-Z]$/.test(str), MK: str => /^(MK)?\d{13}$/.test(str), - AU: str => /^(AU)?\d{11}$/.test(str), + AU, BY: str => /^(УНП )?\d{9}$/.test(str), CA: str => /^(CA)?\d{9}$/.test(str), IS: str => /^(IS)?\d{5,6}$/.test(str), IN: str => /^(IN)?\d{15}$/.test(str), ID: str => /^(ID)?(\d{15}|(\d{2}.\d{3}.\d{3}.\d{1}-\d{3}.\d{3}))$/.test(str), IL: str => /^(IL)?\d{9}$/.test(str), - KZ: str => /^(KZ)?\d{9}$/.test(str), + KZ: str => /^(KZ)?\d{12}$/.test(str), NZ: str => /^(NZ)?\d{9}$/.test(str), NG: str => /^(NG)?(\d{12}|(\d{8}-\d{4}))$/.test(str), NO: str => /^(NO)?\d{9}MVA$/.test(str), diff --git a/src/lib/normalizeEmail.js b/src/lib/normalizeEmail.js index a163bed88..ceb252f34 100644 --- a/src/lib/normalizeEmail.js +++ b/src/lib/normalizeEmail.js @@ -32,6 +32,8 @@ const default_normalize_email_options = { // The following conversions are specific to Yandex // Lowercases the local part of the Yandex address (known to be case-insensitive) yandex_lowercase: true, + // all yandex domains are equal, this explicitly sets the domain to 'yandex.ru' + yandex_convert_yandexru: true, // The following conversions are specific to iCloud // Lowercases the local part of the iCloud address (known to be case-insensitive) @@ -232,7 +234,7 @@ export default function normalizeEmail(email, options) { if (options.all_lowercase || options.yandex_lowercase) { parts[0] = parts[0].toLowerCase(); } - parts[1] = 'yandex.ru'; // all yandex domains are equal, 1st preferred + parts[1] = options.yandex_convert_yandexru ? 'yandex.ru' : parts[1]; } else if (options.all_lowercase) { // Any other address parts[0] = parts[0].toLowerCase(); diff --git a/src/lib/util/assertString.js b/src/lib/util/assertString.js index 948bcba66..3baa4452f 100644 --- a/src/lib/util/assertString.js +++ b/src/lib/util/assertString.js @@ -1,11 +1,4 @@ export default function assertString(input) { - const isString = typeof input === 'string' || input instanceof String; - - if (!isString) { - let invalidType = typeof input; - if (input === null) invalidType = 'null'; - else if (invalidType === 'object') invalidType = input.constructor.name; - - throw new TypeError(`Expected a string but received a ${invalidType}`); - } + if (input === undefined || input === null) throw new TypeError(`Expected a string but received a ${input}`); + if (input.constructor.name !== 'String') throw new TypeError(`Expected a string but received a ${input.constructor.name}`); } diff --git a/src/lib/util/checkHost.js b/src/lib/util/checkHost.js new file mode 100644 index 000000000..ed1dddefe --- /dev/null +++ b/src/lib/util/checkHost.js @@ -0,0 +1,13 @@ +function isRegExp(obj) { + return Object.prototype.toString.call(obj) === '[object RegExp]'; +} + +export default function checkHost(host, matches) { + for (let i = 0; i < matches.length; i++) { + let match = matches[i]; + if (host === match || (isRegExp(match) && match.test(host))) { + return true; + } + } + return false; +} diff --git a/src/lib/util/nullUndefinedCheck.js b/src/lib/util/nullUndefinedCheck.js new file mode 100644 index 000000000..c45bfbe82 --- /dev/null +++ b/src/lib/util/nullUndefinedCheck.js @@ -0,0 +1,3 @@ +export default function isNullOrUndefined(value) { + return value === null || value === undefined; +} diff --git a/test/exports.test.js b/test/exports.test.js index 0bff532ab..a5f458f05 100644 --- a/test/exports.test.js +++ b/test/exports.test.js @@ -6,8 +6,14 @@ import { locales as isAlphanumericLocales } from '../src/lib/isAlphanumeric'; import { locales as isMobilePhoneLocales } from '../src/lib/isMobilePhone'; import { locales as isFloatLocales } from '../src/lib/isFloat'; import { locales as ibanCountryCodes } from '../src/lib/isIBAN'; +import { locales as passportNumberLocales } from '../src/lib/isPassportNumber'; describe('Exports', () => { + it('should export isPassportNumbers\'s supported locales', () => { + assert.ok(passportNumberLocales instanceof Array); + assert.ok(validator.passportNumberLocales instanceof Array); + }); + it('should export validators', () => { assert.strictEqual(typeof validator.isEmail, 'function'); assert.strictEqual(typeof validator.isAlpha, 'function'); diff --git a/test/sanitizers.test.js b/test/sanitizers.test.js index ecb0e128f..e36ba48d3 100644 --- a/test/sanitizers.test.js +++ b/test/sanitizers.test.js @@ -481,5 +481,34 @@ describe('Sanitizers', () => { 'my.self@foo.com': 'my.self@foo.com', }, }); + + // Testing yandex_convert_yandexru + test({ + sanitizer: 'normalizeEmail', + args: [{ + yandex_convert_yandexru: false, + }], + expect: { + 'test@yandex.kz': 'test@yandex.kz', + 'test@yandex.ru': 'test@yandex.ru', + 'test@yandex.ua': 'test@yandex.ua', + 'test@yandex.com': 'test@yandex.com', + 'test@yandex.by': 'test@yandex.by', + }, + }); + + test({ + sanitizer: 'normalizeEmail', + args: [{ + yandex_convert_yandexru: true, + }], + expect: { + 'test@yandex.kz': 'test@yandex.ru', + 'test@yandex.ru': 'test@yandex.ru', + 'test@yandex.ua': 'test@yandex.ru', + 'test@yandex.com': 'test@yandex.ru', + 'test@yandex.by': 'test@yandex.ru', + }, + }); }); }); diff --git a/test/testFunctions.js b/test/testFunctions.js index bcd7c15b0..5fc133bec 100644 --- a/test/testFunctions.js +++ b/test/testFunctions.js @@ -2,6 +2,10 @@ import assert from 'assert'; import { format } from 'util'; import validator from '../src/index'; +function stringifyArgs(argsArr) { + return argsArr.map(arg => JSON.stringify(arg)).join(', '); +} + export default function test(options) { const args = options.args || []; @@ -16,7 +20,7 @@ export default function test(options) { } catch (err) { const warning = format( 'validator.%s(%s) passed but should error', - options.validator, args.join(', ') + options.validator, stringifyArgs(args) ); throw new Error(warning); @@ -31,7 +35,7 @@ export default function test(options) { if (validator[options.validator](...args) !== true) { const warning = format( 'validator.%s(%s) failed but should have passed', - options.validator, args.join(', ') + options.validator, stringifyArgs(args) ); throw new Error(warning); @@ -46,7 +50,7 @@ export default function test(options) { if (validator[options.validator](...args) !== false) { const warning = format( 'validator.%s(%s) passed but should have failed', - options.validator, args.join(', ') + options.validator, stringifyArgs(args) ); throw new Error(warning); diff --git a/test/util.test.js b/test/util.test.js index 449cd9ee7..0146a4e2c 100644 --- a/test/util.test.js +++ b/test/util.test.js @@ -4,6 +4,8 @@ */ import assert from 'assert'; import typeOf from '../src/lib/util/typeOf'; +import assertString from '../src/lib/util/assertString'; + describe('Util', () => { it('should validate different typeOf', () => { @@ -18,3 +20,45 @@ describe('Util', () => { assert.notStrictEqual(typeOf([]), 'object'); }); }); + +describe('assertString', () => { + it('Should throw an error if argument provided is an undefined', () => { + assert.throws(() => { assertString(); }, TypeError); + }); + + it('Should throw an error if argument provided is a null', () => { + assert.throws(() => { assertString(null); }, TypeError); + }); + + it('Should throw an error if argument provided is a Boolean', () => { + assert.throws(() => { assertString(true); }, TypeError); + }); + + it('Should throw an error if argument provided is a Date', () => { + assert.throws(() => { assertString(new Date()); }, TypeError); + }); + + it('Should throw an error if argument provided is a Number(NaN)', () => { + assert.throws(() => { assertString(NaN); }, TypeError); + }); + + it('Should throw an error if argument provided is a Number', () => { + assert.throws(() => { assertString(2024); }, TypeError); + }); + + it('Should throw an error if argument provided is an Object', () => { + assert.throws(() => { assertString({}); }, TypeError); + }); + + it('Should throw an error if argument provided is an Array', () => { + assert.throws(() => { assertString([]); }, TypeError); + }); + + it('Should not throw an error if the argument is an empty string', () => { + assert.doesNotThrow(() => { assertString(''); }); + }); + + it('Should not throw an error if the argument is a String', () => { + assert.doesNotThrow(() => { assertString('antidisestablishmentarianism'); }); + }); +}); diff --git a/test/validators.test.js b/test/validators.test.js index 6c68cd71a..612b103bf 100644 --- a/test/validators.test.js +++ b/test/validators.test.js @@ -1,9 +1,7 @@ import assert from 'assert'; import fs from 'fs'; import timezone_mock from 'timezone-mock'; -import { format } from 'util'; import vm from 'vm'; -import validator from '../src/index'; import test from './testFunctions'; let validator_js = fs.readFileSync(require.resolve('../validator.js')).toString(); @@ -71,6 +69,9 @@ describe('Validators', () => { 'nbsp test@test.com', 'nbsp_test@te st.com', 'nbsp_test@test.co m', + '"foobar@gmail.com', + '"foo"bar@gmail.com', + 'foo"bar"@gmail.com', ], }); }); @@ -265,12 +266,15 @@ describe('Validators', () => { it('should not validate email addresses with blacklisted chars in the name', () => { test({ validator: 'isEmail', - args: [{ blacklisted_chars: 'abc' }], + args: [{ blacklisted_chars: 'abc"' }], valid: [ 'emil@gmail.com', ], invalid: [ 'email@gmail.com', + '"foobr"@example.com', + '" foo m端ller "@example.com', + '"foo\@br"@example.com', ], }); }); @@ -319,6 +323,25 @@ describe('Validators', () => { }); }); + it('should allow regular expressions in the host blacklist of isEmail', () => { + test({ + validator: 'isEmail', + args: [{ + host_blacklist: ['bar.com', 'foo.com', /\.foo\.com$/], + }], + valid: [ + 'email@foobar.com', + 'email@foo.bar.com', + 'email@qux.com', + ], + invalid: [ + 'email@bar.com', + 'email@foo.com', + 'email@a.b.c.foo.com', + ], + }); + }); + it('should validate only email addresses with whitelisted domains', () => { test({ validator: 'isEmail', @@ -335,6 +358,25 @@ describe('Validators', () => { }); }); + it('should allow regular expressions in the host whitelist of isEmail', () => { + test({ + validator: 'isEmail', + args: [{ + host_whitelist: ['bar.com', 'foo.com', /\.foo\.com$/], + }], + valid: [ + 'email@bar.com', + 'email@foo.com', + 'email@a.b.c.foo.com', + ], + invalid: [ + 'email@foobar.com', + 'email@foo.bar.com', + 'email@qux.com', + ], + }); + }); + it('should validate URLs', () => { test({ validator: 'isURL', @@ -784,6 +826,21 @@ describe('Validators', () => { }); }); + it('should allow user to configure the maximum URL length', () => { + test({ + validator: 'isURL', + args: [{ max_allowed_length: 20 }], + valid: [ + 'http://foobar.com/12', // 20 characters + 'http://foobar.com/', + ], + invalid: [ + 'http://foobar.com/123', // 21 characters + 'http://foobar.com/1234567890', + ], + }); + }); + it('should validate URLs with port present', () => { test({ validator: 'isURL', @@ -988,136 +1045,6 @@ describe('Validators', () => { }); }); - it('should validate IP addresses', () => { - test({ - validator: 'isIP', - valid: [ - '127.0.0.1', - '0.0.0.0', - '255.255.255.255', - '1.2.3.4', - '::1', - '2001:db8:0000:1:1:1:1:1', - '2001:db8:3:4::192.0.2.33', - '2001:41d0:2:a141::1', - '::ffff:127.0.0.1', - '::0000', - '0000::', - '1::', - '1111:1:1:1:1:1:1:1', - 'fe80::a6db:30ff:fe98:e946', - '::', - '::8', - '::ffff:127.0.0.1', - '::ffff:255.255.255.255', - '::ffff:0:255.255.255.255', - '::2:3:4:5:6:7:8', - '::255.255.255.255', - '0:0:0:0:0:ffff:127.0.0.1', - '1:2:3:4:5:6:7::', - '1:2:3:4:5:6::8', - '1::7:8', - '1:2:3:4:5::7:8', - '1:2:3:4:5::8', - '1::6:7:8', - '1:2:3:4::6:7:8', - '1:2:3:4::8', - '1::5:6:7:8', - '1:2:3::5:6:7:8', - '1:2:3::8', - '1::4:5:6:7:8', - '1:2::4:5:6:7:8', - '1:2::8', - '1::3:4:5:6:7:8', - '1::8', - 'fe80::7:8%eth0', - 'fe80::7:8%1', - '64:ff9b::192.0.2.33', - '0:0:0:0:0:0:10.0.0.1', - ], - invalid: [ - 'abc', - '256.0.0.0', - '0.0.0.256', - '26.0.0.256', - '0200.200.200.200', - '200.0200.200.200', - '200.200.0200.200', - '200.200.200.0200', - '::banana', - 'banana::', - '::1banana', - '::1::', - '1:', - ':1', - ':1:1:1::2', - '1:1:1:1:1:1:1:1:1:1:1:1:1:1:1:1', - '::11111', - '11111:1:1:1:1:1:1:1', - '2001:db8:0000:1:1:1:1::1', - '0:0:0:0:0:0:ffff:127.0.0.1', - '0:0:0:0:ffff:127.0.0.1', - ], - }); - test({ - validator: 'isIP', - args: [4], - valid: [ - '127.0.0.1', - '0.0.0.0', - '255.255.255.255', - '1.2.3.4', - '255.0.0.1', - '0.0.1.1', - ], - invalid: [ - '::1', - '2001:db8:0000:1:1:1:1:1', - '::ffff:127.0.0.1', - '137.132.10.01', - '0.256.0.256', - '255.256.255.256', - ], - }); - test({ - validator: 'isIP', - args: [6], - valid: [ - '::1', - '2001:db8:0000:1:1:1:1:1', - '::ffff:127.0.0.1', - 'fe80::1234%1', - 'ff08::9abc%10', - 'ff08::9abc%interface10', - 'ff02::5678%pvc1.3', - ], - invalid: [ - '127.0.0.1', - '0.0.0.0', - '255.255.255.255', - '1.2.3.4', - '::ffff:287.0.0.1', - '%', - 'fe80::1234%', - 'fe80::1234%1%3%4', - 'fe80%fe80%', - ], - }); - test({ - validator: 'isIP', - args: [10], - valid: [], - invalid: [ - '127.0.0.1', - '0.0.0.0', - '255.255.255.255', - '1.2.3.4', - '::1', - '2001:db8:0000:1:1:1:1:1', - ], - }); - }); - it('should validate isIPRange', () => { test({ validator: 'isIPRange', @@ -1312,6 +1239,7 @@ describe('Validators', () => { ], }); }); + it('should validate alpha strings', () => { test({ validator: 'isAlpha', @@ -2048,6 +1976,45 @@ describe('Validators', () => { }); }); + it('should validate Esperanto alpha strings', () => { + test({ + validator: 'isAlpha', + args: ['eo'], + valid: [ + 'saluton', + 'eĥoŝanĝoĉiuĵaŭde', + 'EĤOŜANĜOĈIUĴAŬDE', + 'Esperanto', + 'LaŭLudovikoZamenhofBongustasFreŝaĈeĥaManĝaĵoKunSpicoj', + ], + invalid: [ + 'qwxyz', + '1887', + 'qwxyz 1887', + ], + }); + }); + + it('should validate Irish alpha strings', () => { + test({ + validator: 'isAlpha', + args: ['ga-IE'], + valid: [ + 'Éire', + 'Císte', + 'Seán', + 'Réabhlóidithe', + 'ceiliúradh', + 'Buachaill', + ], + invalid: [ + 'Éire1', + ' Císte ', + '123', + ], + }); + }); + it('should error on invalid locale', () => { test({ validator: 'isAlpha', @@ -2735,6 +2702,45 @@ describe('Validators', () => { }); }); + it('should validate Esperanto alphanumeric strings', () => { + test({ + validator: 'isAlphanumeric', + args: ['eo'], + valid: [ + 'saluton', + 'eĥoŝanĝoĉiuĵaŭde0123456789', + 'EĤOŜANĜOĈIUĴAŬDE0123456789', + 'Esperanto1887', + 'LaŭLudovikoZamenhofBongustasFreŝaĈeĥaManĝaĵoKunSpicoj', + ], + invalid: [ + 'qwxyz', + 'qwxyz 1887', + ], + }); + }); + + it('should validate Irish alphanumeric strings', () => { + test({ + validator: 'isAlphanumeric', + args: ['ga-IE'], + valid: [ + 'Éire123', + '4Císte', + 'S5eán', + 'Réabhlóidithe', + 'ceiliúradh', + 'Buachaill', + '678', + ], + invalid: [ + 'Éire 1', + ' Císte 2 ', + '123!', + ], + }); + }); + it('should error on invalid locale', () => { test({ validator: 'isAlphanumeric', @@ -2855,6 +2861,7 @@ describe('Validators', () => { '', '-1', '65536', + '0080', ], }); }); @@ -2926,11 +2933,11 @@ describe('Validators', () => { validator: 'isPassportNumber', args: ['AZ'], valid: [ - 'AZE16175905', - 'AA1617595', + 'A16175905', + 'A16175958', ], invalid: [ - 'A12345843', + 'AZ1234584', ], }); @@ -2988,9 +2995,17 @@ describe('Validators', () => { valid: [ 'GA302922', 'ZE000509', + 'A123456AB', + 'Z556378HG', ], invalid: [ 'AB0123456', + 'AZ556378H', + '556378HCX', + '556378432', + '5563784', + '#B12345FD', + 'A43F12354', ], }); @@ -3648,6 +3663,21 @@ describe('Validators', () => { '7903699371', ], }); + + test({ + validator: 'isPassportNumber', + args: ['ZA'], + valid: [ + 'T12345678', + 'A12345678', + 'M12345678', + 'D12345678', + ], + invalid: [ + '123456789', + 'Z12345678', + ], + }); }); it('should validate decimal numbers', () => { @@ -4155,6 +4185,78 @@ describe('Validators', () => { 'a', ], }); + test({ + validator: 'isInt', + args: [{ + min: undefined, + max: undefined, + }], + valid: [ + '143', + '15', + '767777575', + ], + invalid: [ + '10.4', + 'bar', + '10a', + 'c44', + ], + }); + test({ + validator: 'isInt', + args: [{ + gt: undefined, + lt: undefined, + }], + valid: [ + '289373466', + '55', + '989', + ], + invalid: [ + '10.4', + 'baz', + '66a', + 'c21', + ], + }); + test({ + validator: 'isInt', + args: [{ + gt: null, + max: null, + }], + valid: [ + '1', + '886', + '84512345', + ], + invalid: [ + '10.4', + 'h', + '1.2', + '+', + ], + }); + test({ + validator: 'isInt', + args: [{ + lt: null, + min: null, + }], + valid: [ + '289373466', + '55', + '989', + ], + invalid: [ + ',', + '+11212+', + 'fail', + '111987234i', + ], + }); }); it('should validate floats', () => { @@ -4384,6 +4486,87 @@ describe('Validators', () => { 'foo', ], }); + test({ + validator: 'isFloat', + args: [{ + min: undefined, + max: undefined, + }], + valid: [ + '123', + '123.', + '123.123', + '-767.767', + '+111.111', + ], + invalid: [ + 'ab565', + '-,123', + '+,123', + '7866.t', + '123,123', + '123,', + ], + }); + test({ + validator: 'isFloat', + args: [{ + gt: undefined, + lt: undefined, + }], + valid: [ + '14.34343', + '11.1', + '456', + ], + invalid: [ + 'ab565', + '-,123', + '+,123', + '7866.t', + ], + }); + test({ + validator: 'isFloat', + args: [{ + locale: 'ar', + gt: null, + max: null, + }], + valid: [ + '13324٫', + '12321', + '444٫83874', + ], + invalid: [ + '55.55.55', + '1;23', + '+-123', + '1111111l1', + '3.3', + ], + }); + test({ + validator: 'isFloat', + args: [{ + locale: 'ru-RU', + lt: null, + min: null, + }], + valid: [ + '11231554,34343', + '11,1', + '456', + ',311', + ], + invalid: [ + 'ab565', + '-.123', + '+.123', + '7866.t', + '22.3', + ], + }); }); it('should validate hexadecimal strings', () => { @@ -4508,8 +4691,10 @@ describe('Validators', () => { 'rgba(255,255,255,1)', 'rgba(255,255,255,.1)', 'rgba(255,255,255,0.1)', + 'rgba(255,255,255,.12)', 'rgb(5%,5%,5%)', 'rgba(5%,5%,5%,.3)', + 'rgba(5%,5%,5%,.32)', ], invalid: [ 'rgb(0,0,0,)', @@ -4518,18 +4703,63 @@ describe('Validators', () => { 'rgb()', 'rgba(0,0,0)', 'rgba(255,255,255,2)', - 'rgba(255,255,255,.12)', + 'rgba(255,255,255,.123)', 'rgba(255,255,256,0.1)', 'rgb(4,4,5%)', 'rgba(5%,5%,5%)', 'rgba(3,3,3%,.3)', + 'rgba(5%,5%,5%,.321)', 'rgb(101%,101%,101%)', 'rgba(3%,3%,101%,0.3)', 'rgb(101%,101%,101%) additional invalid string part', 'rgba(3%,3%,101%,0.3) additional invalid string part', + 'r g b( 0, 251, 222 )', + 'r g ba( 0, 251, 222 )', + 'rg ba(0, 251, 22, 0.5)', + 'rgb( 255,255 ,255)', + 'rgba(255, 255, 255, 0.5)', + 'rgba(255, 255, 255, 0.5)', + 'rgb(5%, 5%, 5%)', ], }); + // test empty options object + test({ + validator: 'isRgbColor', + args: [{}], + valid: [ + 'rgb(0,0,0)', + 'rgb(255,255,255)', + 'rgba(0,0,0,0)', + 'rgba(255,255,255,1)', + 'rgba(255,255,255,.1)', + 'rgba(255,255,255,0.1)', + 'rgb(5%,5%,5%)', + 'rgba(5%,5%,5%,.3)', + ], + invalid: [ + 'rgb(0,0,0,)', + 'rgb(0,0,)', + 'rgb(0,0,256)', + 'rgb()', + 'rgba(0,0,0)', + 'rgba(255,255,255,2)', + 'rgba(255,255,255,.12)', + 'rgba(255,255,256,0.1)', + 'rgb(4,4,5%)', + 'rgba(5%,5%,5%)', + 'rgba(3,3,3%,.3)', + 'rgb(101%,101%,101%)', + 'rgba(3%,3%,101%,0.3)', + 'r g b( 0, 251, 222 )', + 'r g ba( 0, 251, 222 )', + 'rg ba(0, 251, 22, 0.5)', + 'rgb( 255,255 ,255)', + 'rgba(255, 255, 255, 0.5)', + 'rgba(255, 255, 255, 0.5)', + 'rgb(5%, 5%, 5%)', + ], + }); // test where includePercentValues is given as false test({ validator: 'isRgbColor', @@ -4541,6 +4771,159 @@ describe('Validators', () => { invalid: [ 'rgb(4,4,5%)', 'rgba(5%,5%,5%)', + 'r g b( 0, 251, 222 )', + 'r g ba( 0, 251, 222 )', + ], + }); + + // test where includePercentValues is given as false as part of options object + test({ + validator: 'isRgbColor', + args: [{ includePercentValues: false }], + valid: [ + 'rgb(5,5,5)', + 'rgba(5,5,5,.3)', + ], + invalid: [ + 'rgb(4,4,5%)', + 'rgba(5%,5%,5%)', + 'r g b( 0, 251, 222 )', + 'rgba(255, 255, 255 ,0.2)', + 'r g ba( 0, 251, 222 )', + ], + }); + + // test where include percent is true explciitly + test({ + validator: 'isRgbColor', + args: [true], + valid: [ + 'rgb(5,5,5)', + 'rgba(5,5,5,.3)', + 'rgb(0,0,0)', + 'rgb(255,255,255)', + 'rgba(0,0,0,0)', + 'rgba(255,255,255,1)', + 'rgba(255,255,255,.1)', + 'rgba(255,255,255,0.1)', + 'rgb(5%,5%,5%)', + 'rgba(5%,5%,5%,.3)', + 'rgb(5%,5%,5%)', + 'rgba(255,255,255,0.5)', + ], + invalid: [ + 'rgba(255, 255, 255, 0.5)', + 'rgb(5%, 5%, 5%)', + 'rgb(4,4,5%)', + 'rgba(5%,5%,5%)', + 'r g b( 0, 251, 222 )', + 'r g ba( 0, 251, 222 )', + 'rgb(0,0,0,)', + 'rgb(0,0,)', + 'rgb(0,0,256)', + 'rgb()', + 'rgba(0,0,0)', + 'rgba(255,255,255,2)', + 'rgba(255,255,255,.12)', + 'rgba(255,255,256,0.1)', + 'rgb(4,4,5%)', + 'rgba(5%,5%,5%)', + 'rgba(3,3,3%,.3)', + 'rgb(101%,101%,101%)', + 'rgba(3%,3%,101%,0.3)', + ], + }); + + // test where percent value is false and allowSpaces is true as part of options object + test({ + validator: 'isRgbColor', + args: [{ includePercentValues: false, allowSpaces: true }], + valid: [ + 'rgb(5,5,5)', + 'rgba(5,5,5,.3)', + 'rgba(255,255,255,0.2)', + 'rgba(255, 255, 255 ,0.2)', + ], + invalid: [ + 'rgb(4,4,5%)', + 'rgba(5%,5%,5%)', + 'rgba(5% ,5%, 5%)', + 'r g b( 0, 251, 222 )', + 'r g ba( 0, 251, 222 )', + 'rgb(0,0,)', + 'rgb()', + 'rgb(4,4,5%)', + 'rgb(5%,5%,5%)', + 'rgba(3,3,3%,.3)', + 'rgb(101%, 101%, 101%)', + 'rgba(3%,3%,101%,0.3)', + ], + + }); + + // test where both are true as part of options object + test({ + validator: 'isRgbColor', + args: [{ includePercentValues: true, allowSpaces: true }], + valid: [ + 'rgb( 5, 5, 5)', + 'rgba(5, 5, 5, .3)', + 'rgb(0, 0, 0)', + 'rgb(255, 255, 255)', + 'rgba(0, 0, 0, 0)', + 'rgba(255, 255, 255, 1)', + 'rgba(255, 255, 255, .1)', + 'rgba(255, 255, 255, 0.1)', + 'rgb(5% ,5% ,5%)', + 'rgba(5%,5%,5%, .3)', + ], + invalid: [ + 'r g b( 0, 251, 222 )', + 'rgb(4,4,5%)', + 'rgb(101%,101%,101%)', + + ], + }); + + // test where allowSpaces is false as part of options object + test({ + validator: 'isRgbColor', + args: [{ includePercentValues: true, allowSpaces: false }], + valid: [ + 'rgb(5,5,5)', + 'rgba(5,5,5,.3)', + 'rgb(0,0,0)', + 'rgb(255,255,255)', + 'rgba(0,0,0,0)', + 'rgba(255,255,255,1)', + 'rgba(255,255,255,.1)', + 'rgba(255,255,255,0.1)', + 'rgb(5%,5%,5%)', + 'rgba(5%,5%,5%,.3)', + + ], + invalid: [ + 'rgb( 255,255 ,255)', + 'rgba(255, 255, 255, 0.5)', + 'rgb(5%, 5%, 5%)', + 'rgba(255, 255, 255, 0.5)', + 'rgb(4,4,5%)', + 'rgba(5%,5%,5%)', + 'r g b( 0, 251, 222 )', + 'r g ba( 0, 251, 222 )', + 'rgb(0,0,0,)', + 'rgb(0,0,)', + 'rgb(0,0,256)', + 'rgb()', + 'rgba(0,0,0)', + 'rgba(255,255,255,2)', + 'rgba(255,255,255,.12)', + 'rgba(255,255,256,0.1)', + 'rgb(4,4,5%)', + 'rgba(5%,5%,5%)', + 'rgba(3,3,3%,.3)', + 'rgb(101%,101%,101%)', + 'rgba(3%,3%,101%,0.3)', ], }); }); @@ -4970,12 +5353,42 @@ describe('Validators', () => { valid: ['abc', 'de', 'a', ''], invalid: ['abcd'], }); + test({ + validator: 'isLength', + args: [{ max: 6, discreteLengths: 5 }], + valid: ['abcd', 'vfd', 'ff', '', 'k'], + invalid: ['abcdefgh', 'hfjdksks'], + }); + test({ + validator: 'isLength', + args: [{ min: 2, max: 6, discreteLengths: 5 }], + valid: ['bsa', 'vfvd', 'ff'], + invalid: ['', ' ', 'hfskdunvc'], + }); + test({ + validator: 'isLength', + args: [{ min: 1, discreteLengths: 2 }], + valid: [' ', 'hello', 'bsa'], + invalid: [''], + }); test({ validator: 'isLength', args: [{ max: 0 }], valid: [''], invalid: ['a', 'ab'], }); + test({ + validator: 'isLength', + args: [{ min: 5, max: 10, discreteLengths: [2, 6, 8, 9] }], + valid: ['helloguy', 'shopping', 'validator', 'length'], + invalid: ['abcde', 'abcdefg'], + }); + test({ + validator: 'isLength', + args: [{ discreteLengths: '9' }], + valid: ['a', 'abcd', 'abcdefghijkl'], + invalid: [], + }); test({ validator: 'isLength', valid: ['a', '', 'asds'], @@ -5014,17 +5427,44 @@ describe('Validators', () => { }); }); + it('should validate ULIDs', () => { + test({ + validator: 'isULID', + valid: [ + '01HBGW8CWQ5Q6DTT7XP89VV4KT', + '01HBGW8CWR8MZQMBG6FA2QHMDD', + '01HBGW8CWS3MEEK12Y9G7SVW4V', + '01hbgw8cws1tq2njavy9amb0wx', + '01HBGW8cwS43H4jkQ0A4ZRJ7QV', + ], + invalid: [ + '', + '01HBGW-CWS3MEEK1#Y9G7SVW4V', + '91HBGW8CWS3MEEK12Y9G7SVW4V', + '81HBGW8CWS3MEEK12Y9G7SVW4V', + '934859', + '01HBGW8CWS3MEEK12Y9G7SVW4VXXX', + '01UBGW8IWS3MOEK12Y9G7SVW4V', + '01HBGW8CuS43H4JKQ0A4ZRJ7QV', + ], + }); + }); + it('should validate UUIDs', () => { test({ validator: 'isUUID', valid: [ - 'A987FBC9-4BED-3078-CF07-9141BA07C9F3', + '9deb20fe-a6e0-355c-81ea-288b009e4f6d', 'A987FBC9-4BED-4078-8F07-9141BA07C9F3', 'A987FBC9-4BED-5078-AF07-9141BA07C9F3', + 'A987FBC9-4BED-6078-AF07-9141BA07C9F3', + '018C544A-D384-7000-BB74-3B1738ABE43C', + 'A987FBC9-4BED-8078-AF07-9141BA07C9F3', ], invalid: [ '', 'xxxA987FBC9-4BED-3078-CF07-9141BA07C9F3', + 'A987FBC9-4BED-3078-CF07-9141BA07C9F3', 'A987FBC9-4BED-3078-CF07-9141BA07C9F3xxx', 'A987FBC94BED3078CF079141BA07C9F3', '934859', @@ -5036,11 +5476,13 @@ describe('Validators', () => { validator: 'isUUID', args: [undefined], valid: [ - 'A117FBC9-4BED-3078-CF07-9141BA07C9F3', + '9deb20fe-a6e0-355c-81ea-288b009e4f6d', 'A117FBC9-4BED-5078-AF07-9141BA07C9F3', + '018C544A-D384-7000-BB74-3B1738ABE43C', ], invalid: [ '', + 'A117FBC9-4BED-3078-CF07-9141BA07C9F3', 'xxxA987FBC9-4BED-3078-CF07-9141BA07C9F3', 'A987FBC94BED3078CF079141BA07C9F3', 'A11AAAAA-1111-1111-AAAG-111111111111', @@ -5050,11 +5492,13 @@ describe('Validators', () => { validator: 'isUUID', args: [null], valid: [ - 'A127FBC9-4BED-3078-CF07-9141BA07C9F3', + 'A127FBC9-4BED-3078-AF07-9141BA07C9F3', + '018C544A-D384-7000-BB74-3B1738ABE43C', ], invalid: [ '', 'xxxA987FBC9-4BED-3078-CF07-9141BA07C9F3', + 'A127FBC9-4BED-3078-CF07-9141BA07C9F3', 'A127FBC9-4BED-3078-CF07-9141BA07C9F3xxx', '912859', 'A12AAAAA-1111-1111-AAAG-111111111111', @@ -5072,36 +5516,41 @@ describe('Validators', () => { 'AAAAAAAA-1111-2222-AAAG-111111111111', 'A987FBC9-4BED-4078-8F07-9141BA07C9F3', 'A987FBC9-4BED-5078-AF07-9141BA07C9F3', + '018C544A-D384-7000-BB74-3B1738ABE43C', ], }); test({ validator: 'isUUID', args: [2], valid: [ - 'A987FBC9-4BED-2078-CF07-9141BA07C9F3', + 'A987FBC9-4BED-2078-AF07-9141BA07C9F3', ], invalid: [ '', 'xxxA987FBC9-4BED-3078-CF07-9141BA07C9F3', '11111', 'AAAAAAAA-1111-1111-AAAG-111111111111', + 'A987FBC9-4BED-2078-CF07-9141BA07C9F3', 'A987FBC9-4BED-4078-8F07-9141BA07C9F3', 'A987FBC9-4BED-5078-AF07-9141BA07C9F3', + '018C544A-D384-7000-BB74-3B1738ABE43C', ], }); test({ validator: 'isUUID', args: [3], valid: [ - 'A987FBC9-4BED-3078-CF07-9141BA07C9F3', + '9deb20fe-a6e0-355c-81ea-288b009e4f6d', ], invalid: [ '', + 'A987FBC9-4BED-3078-CF07-9141BA07C9F3', 'xxxA987FBC9-4BED-3078-CF07-9141BA07C9F3', '934859', 'AAAAAAAA-1111-1111-AAAG-111111111111', 'A987FBC9-4BED-4078-8F07-9141BA07C9F3', 'A987FBC9-4BED-5078-AF07-9141BA07C9F3', + '018C544A-D384-7000-BB74-3B1738ABE43C', ], }); test({ @@ -5120,36 +5569,84 @@ describe('Validators', () => { 'AAAAAAAA-1111-1111-AAAG-111111111111', 'A987FBC9-4BED-5078-AF07-9141BA07C9F3', 'A987FBC9-4BED-3078-CF07-9141BA07C9F3', + '018C544A-D384-7000-BB74-3B1738ABE43C', + ], + }); + test({ + validator: 'isUUID', + args: [5], + valid: [ + '987FBC97-4BED-5078-AF07-9141BA07C9F3', + '987FBC97-4BED-5078-BF07-9141BA07C9F3', + '987FBC97-4BED-5078-8F07-9141BA07C9F3', + '987FBC97-4BED-5078-9F07-9141BA07C9F3', + ], + invalid: [ + '', + 'xxxA987FBC9-4BED-3078-CF07-9141BA07C9F3', + '934859', + 'AAAAAAAA-1111-1111-AAAG-111111111111', + '9c858901-8a57-4791-81fe-4c455b099bc9', + 'A987FBC9-4BED-3078-CF07-9141BA07C9F3', + '018C544A-D384-7000-BB74-3B1738ABE43C', + ], + }); + test({ + validator: 'isUUID', + args: [6], + valid: [ + '1ef29908-cde1-69d0-be16-bfc8518a95f0', + ], + invalid: [ + '987FBC97-4BED-1078-AF07-9141BA07C9F3', + '987FBC97-4BED-2078-AF07-9141BA07C9F3', + '987FBC97-4BED-3078-AF07-9141BA07C9F3', + '987FBC97-4BED-4078-AF07-9141BA07C9F3', + '987FBC97-4BED-5078-AF07-9141BA07C9F3', + '018C544A-D384-7000-BB74-3B1738ABE43C', + '987FBC97-4BED-8078-AF07-9141BA07C9F3', + ], + }); + test({ + validator: 'isUUID', + args: [7], + valid: [ + '018C544A-D384-7000-BB74-3B1738ABE43C', + ], + invalid: [ + '', + 'xxxA987FBC9-4BED-3078-CF07-9141BA07C9F3', + '934859', + 'AAAAAAAA-1111-1111-AAAG-111111111111', + 'A987FBC9-4BED-5078-AF07-9141BA07C9F3', + 'A987FBC9-4BED-3078-CF07-9141BA07C9F3', + 'A987FBC9-4BED-6078-AF07-9141BA07C9F3', + 'A987FBC9-4BED-8078-AF07-9141BA07C9F3', + '713ae7e3-cb32-45f9-adcb-7c4fa86b90c1', + '625e63f3-58f5-40b7-83a1-a72ad31acffb', + '57b73598-8764-4ad0-a76a-679bb6640eb1', + '9c858901-8a57-4791-81fe-4c455b099bc9', ], }); test({ validator: 'isUUID', - args: [5], + args: [8], valid: [ - '987FBC97-4BED-5078-AF07-9141BA07C9F3', - '987FBC97-4BED-5078-BF07-9141BA07C9F3', - '987FBC97-4BED-5078-8F07-9141BA07C9F3', - '987FBC97-4BED-5078-9F07-9141BA07C9F3', + '018C544A-D384-8000-BB74-3B1738ABE43C', ], invalid: [ '', 'xxxA987FBC9-4BED-3078-CF07-9141BA07C9F3', '934859', 'AAAAAAAA-1111-1111-AAAG-111111111111', - '9c858901-8a57-4791-81fe-4c455b099bc9', + 'A987FBC9-4BED-5078-AF07-9141BA07C9F3', 'A987FBC9-4BED-3078-CF07-9141BA07C9F3', - ], - }); - test({ - validator: 'isUUID', - args: [6], - valid: [], - invalid: [ - '987FBC97-4BED-1078-AF07-9141BA07C9F3', - '987FBC97-4BED-2078-AF07-9141BA07C9F3', - '987FBC97-4BED-3078-AF07-9141BA07C9F3', - '987FBC97-4BED-4078-AF07-9141BA07C9F3', - '987FBC97-4BED-5078-AF07-9141BA07C9F3', + 'A987FBC9-4BED-6078-AF07-9141BA07C9F3', + 'A987FBC9-4BED-7078-AF07-9141BA07C9F3', + '713ae7e3-cb32-45f9-adcb-7c4fa86b90c1', + '625e63f3-58f5-40b7-83a1-a72ad31acffb', + '57b73598-8764-4ad0-a76a-679bb6640eb1', + '9c858901-8a57-4791-81fe-4c455b099bc9', ], }); }); @@ -5197,38 +5694,23 @@ describe('Validators', () => { }); }); - it('should validate dates against an end date', () => { - test({ - validator: 'isBefore', - args: ['08/04/2011'], - valid: ['2010-07-02', '2010-08-04', new Date(0).toString()], - invalid: ['08/04/2011', new Date(2011, 9, 10).toString()], - }); + it('should validate ABA routing number', () => { test({ - validator: 'isBefore', - args: [new Date(2011, 7, 4).toString()], - valid: ['2010-07-02', '2010-08-04', new Date(0).toString()], - invalid: ['08/04/2011', new Date(2011, 9, 10).toString()], - }); - test({ - validator: 'isBefore', + validator: 'isAbaRouting', valid: [ - '2000-08-04', - new Date(0).toString(), - new Date(Date.now() - 86400000).toString(), + '322070381', + '011103093', + '263170175', + '124303065', + ], + invalid: [ + '426317017', + '789456124', + '603558459', + 'qwerty', + '12430306', + '382070381', ], - invalid: ['2100-07-02', new Date(2217, 10, 10).toString()], - }); - test({ - validator: 'isBefore', - args: ['2011-08-03'], - valid: ['1999-12-31'], - invalid: ['invalid date'], - }); - test({ - validator: 'isBefore', - args: ['invalid date'], - invalid: ['invalid date', '1999-12-31'], }); }); @@ -5259,6 +5741,11 @@ describe('Validators', () => { 'IR200170000000339545727003', 'MZ97123412341234123412341', 'MA64011519000001205000534921', + 'VG96VPVG0000012345678901', + 'DZ580002100001113000000570', + 'IE29AIBK93115212345678', + 'PS92PALS000000000400123456702', + 'PS92PALS00000000040012345670O', ], invalid: [ 'XX22YYY1234567890123', @@ -5266,6 +5753,9 @@ describe('Validators', () => { 'FR7630006000011234567890189@', 'FR7630006000011234567890189😅', 'FR763000600001123456!!🤨7890189@', + 'VG46H07Y0223060094359858', + 'IE95TE8270900834048660', + 'PS072435171802145240705922007', ], }); test({ @@ -5727,6 +6217,28 @@ describe('Validators', () => { it('should validate identity cards', () => { const fixtures = [ + { + locale: 'PK', + valid: [ + '45504-4185771-3', + '39915-6182971-9', + '21143-6182971-2', + '34543-2323471-1', + '72345-2345678-7', + '63456-8765432-8', + '55672-1234567-5', + '21234-9876543-6', + ], + invalid: [ + '08000-1234567-5', + '74321-87654321-1', + '51234-98765-2', + '00000-0000000-0', + '88888-88888888-0', + '99999-9999999-9', + '11111', + ], + }, { locale: 'zh-HK', valid: [ @@ -6520,76 +7032,6 @@ describe('Validators', () => { }); }); - it('should validate base64 strings', () => { - test({ - validator: 'isBase64', - valid: [ - '', - 'Zg==', - 'Zm8=', - 'Zm9v', - 'Zm9vYg==', - 'Zm9vYmE=', - 'Zm9vYmFy', - 'TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQsIGNvbnNlY3RldHVyIGFkaXBpc2NpbmcgZWxpdC4=', - 'Vml2YW11cyBmZXJtZW50dW0gc2VtcGVyIHBvcnRhLg==', - 'U3VzcGVuZGlzc2UgbGVjdHVzIGxlbw==', - 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuMPNS1Ufof9EW/M98FNw' + - 'UAKrwflsqVxaxQjBQnHQmiI7Vac40t8x7pIb8gLGV6wL7sBTJiPovJ0V7y7oc0Ye' + - 'rhKh0Rm4skP2z/jHwwZICgGzBvA0rH8xlhUiTvcwDCJ0kc+fh35hNt8srZQM4619' + - 'FTgB66Xmp4EtVyhpQV+t02g6NzK72oZI0vnAvqhpkxLeLiMCyrI416wHm5Tkukhx' + - 'QmcL2a6hNOyu0ixX/x2kSFXApEnVrJ+/IxGyfyw8kf4N2IZpW5nEP847lpfj0SZZ' + - 'Fwrd1mnfnDbYohX2zRptLy2ZUn06Qo9pkG5ntvFEPo9bfZeULtjYzIl6K8gJ2uGZ' + - 'HQIDAQAB', - ], - invalid: [ - '12345', - 'Vml2YW11cyBmZXJtZtesting123', - 'Zg=', - 'Z===', - 'Zm=8', - '=m9vYg==', - 'Zm9vYmFy====', - ], - }); - - test({ - validator: 'isBase64', - args: [{ urlSafe: true }], - valid: [ - '', - 'bGFkaWVzIGFuZCBnZW50bGVtZW4sIHdlIGFyZSBmbG9hdGluZyBpbiBzcGFjZQ', - '1234', - 'bXVtLW5ldmVyLXByb3Vk', - 'PDw_Pz8-Pg', - 'VGhpcyBpcyBhbiBlbmNvZGVkIHN0cmluZw', - ], - invalid: [ - ' AA', - '\tAA', - '\rAA', - '\nAA', - 'This+isa/bad+base64Url==', - '0K3RgtC+INC30LDQutC+0LTQuNGA0L7QstCw0L3QvdCw0Y8g0YHRgtGA0L7QutCw', - ], - error: [ - null, - undefined, - {}, - [], - 42, - ], - }); - - for (let i = 0, str = '', encoded; i < 1000; i++) { - str += String.fromCharCode(Math.random() * 26 | 97); // eslint-disable-line no-bitwise - encoded = Buffer.from(str).toString('base64'); - if (!validator.isBase64(encoded)) { - let msg = format('validator.isBase64() failed with "%s"', encoded); - throw new Error(msg); - } - } - }); it('should validate hex-encoded MongoDB ObjectId', () => { test({ @@ -6632,20 +7074,39 @@ describe('Validators', () => { { locale: 'am-AM', valid: [ - '+37410324123', - '+37422298765', - '+37431276521', - '022698763', - '37491987654', - '+37494567890', + '+37433123456', + '+37441123456', + '+37443123456', + '+37444123456', + '+37455123456', + '+37477123456', + '+37488123456', + '+37491123456', + '+37493123456', + '+37494123456', + '+37495123456', + '+37496123456', + '+37498123456', + '+37499123456', + '055123456', + '37455123456', ], invalid: [ '12345', - '+37411498855', - '+37411498123', + '+37403498855', + '+37416498123', '05614988556', '', '37456789000', + '37486789000', + '+37431312345', + '+37430312345', + '+37460123456', + '+37410324123', + '+37422298765', + '+37431276521', + '022698763', + '+37492123456', ], }, { @@ -6880,6 +7341,7 @@ describe('Validators', () => { locale: 'ar-OM', valid: [ '+96891212121', + '+96871212121', '0096899999999', '93112211', '99099009', @@ -7451,6 +7913,7 @@ describe('Validators', () => { '0502345671', '0242345671', '0542345671', + '0532345671', '0272345671', '0572345671', '0262345671', @@ -7461,6 +7924,7 @@ describe('Validators', () => { '+233502345671', '+233242345671', '+233542345671', + '+233532345671', '+233272345671', '+233572345671', '+233262345671', @@ -8072,6 +8536,11 @@ describe('Validators', () => { '+3599148725', '96537247', '3596676533', + '+35795123455', + '+35797012204', + '35799123456', + '+35794123456', + '+35796123456', ], invalid: [ '', @@ -8100,6 +8569,9 @@ describe('Validators', () => { '+443003434751', '05073456754', '08001123123', + '07043425232', + '01273884231', + '03332654034', ], }, { @@ -8172,6 +8644,8 @@ describe('Validators', () => { '+260966684590', '+260976684590', '260976684590', + '+260779493521', + '+260760010936', ], invalid: [ '12345', @@ -8179,6 +8653,7 @@ describe('Validators', () => { 'Vml2YW11cyBmZXJtZtesting123', '010-38238383', '966684590', + '760010936', ], }, { @@ -8961,15 +9436,44 @@ describe('Validators', () => { { locale: 'ky-KG', valid: [ - '+7 727 123 4567', - '+7 714 2396102', - '77271234567', - '0271234567', - ], - invalid: [ - '02188565377', - '09386932778', - '0938693277vadggjdsaasdgj8', + '+996553033300', + '+996 222 123456', + '+996 500 987654', + '+996 555 111222', + '+996 700 333444', + '+996 770 555666', + '+996 880 777888', + '+996 990 999000', + '+996 995 555666', + '+996 996 555666', + '+996 997 555666', + '+996 998 555666', + ], + invalid: [ + '+996 201 123456', + '+996 312 123456', + '+996 3960 12345', + '+996 3961 12345', + '+996 3962 12345', + '+996 3963 12345', + '+996 3964 12345', + '+996 3965 12345', + '+996 3966 12345', + '+996 3967 12345', + '+996 3968 12345', + '+996 511 123456', + '+996 522 123456', + '+996 561 123456', + '+996 571 123456', + '+996 624 123456', + '+996 623 123456', + '+996 622 123456', + '+996 609 123456', + '+996 100 12345', + '+996 100 1234567', + '996 100 123456', + '0 100 123456', + '0 100 123abc', ], }, { @@ -9303,16 +9807,67 @@ describe('Validators', () => { { locale: 'uk-UA', valid: [ - '+380982345679', - '380982345679', - '80982345679', - '0982345679', + '+380501234567', + '+380631234567', + '+380661234567', + '+380671234567', + '+380681234567', + '+380731234567', + '+380751234567', + '+380771234567', + '+380911234567', + '+380921234567', + '+380931234567', + '+380941234567', + '+380951234567', + '+380961234567', + '+380971234567', + '+380981234567', + '+380991234567', + '380501234567', + '380631234567', + '380661234567', + '380671234567', + '380681234567', + '380731234567', + '380751234567', + '380771234567', + '380911234567', + '380921234567', + '380931234567', + '380941234567', + '380951234567', + '380961234567', + '380971234567', + '380981234567', + '380991234567', + '0501234567', + '0631234567', + '0661234567', + '0671234567', + '0681234567', + '0731234567', + '0751234567', + '0771234567', + '0911234567', + '0921234567', + '0931234567', + '0941234567', + '0951234567', + '0961234567', + '0971234567', + '0981234567', + '0991234567', ], invalid: [ '+30982345679', + '+380321234567', + '+380441234567', '982345679', + '80982345679', '+380 98 234 5679', '+380-98-234-5679', + '+380 (98) 234-56-79', '', 'ASDFGJKLmZXJtZtesting123', '123456', @@ -9608,15 +10163,27 @@ describe('Validators', () => { { locale: 'sq-AL', valid: [ - '067123456', - '+35567123456', + '0621234567', + '0661234567', + '0671234567', + '0681234567', + '0691234567', + '+355621234567', + '+355651234567', + '+355661234567', + '+355671234567', + '+355681234567', + '+355691234567', ], invalid: [ '67123456', '06712345', + '067123456', '06712345678', - '065123456', - '057123456', + '0571234567', + '+3556712345', + '+35565123456', + '+35157123456', 'NotANumber', ], }, @@ -9637,10 +10204,12 @@ describe('Validators', () => { locale: 'pt-AO', valid: [ '+244911123432', - '+244123091232', + '911123432', + '244911123432', ], invalid: [ '+2449111234321', + '+244811123432', '31234', '31234567', '512345', @@ -9980,6 +10549,56 @@ describe('Validators', () => { ], }, + { + locale: 'es-GT', + valid: [ + '+50221234567', + '+50277654321', + '50226753421', + '50272332468', + '50278984455', + '+50273472492', + '71234567', + '21132398', + ], + invalid: [ + '44', + '+5022712345678', + '1234567899', + '502712345678', + 'This should fail', + '5021931234567', + '+50281234567', + ], + }, + { + locale: 'mk-MK', + valid: [ + '+38923234567', + '38931234567', + '022123456', + '22234567', + '71234567', + '31234567', + '+38923091500', + '80091234', + '81123456', + '54123456', + ], + invalid: [ + '38912345678', + '+389123456789', + '21234567', + '123456789', + '+3891234567', + '700012345', + '510123456', + 'This should fail', + '+389123456', + '389123456', + '80912345', + ], + }, ]; let allValid = []; @@ -11033,19 +11652,34 @@ describe('Validators', () => { validator: 'isBtcAddress', valid: [ '1MUz4VMYui5qY1mxUiG8BQ1Luv6tqkvaiL', + 'mucFNhKMYoBQYUAEsrFVscQ1YaFQPekBpg', '3J98t1WpEZ73CNmQviecrnyiWrnqRhWNLy', + '2NFUBBRcTJbYc1D4HSCbJhKZp6YCV4PQFpQ', 'bc1qar0srrr7xfkvy5l643lydnw9re59gtzzwf5mdq', '14qViLJfdGaP4EeHnDyJbEGQysnCpwk3gd', '35bSzXvRKLpHsHMrzb82f617cV4Srnt7hS', '17VZNX1SN5NtKa8UQFxwQbFeFc3iqRYhemt', 'bc1qw508d6qejxtdg4y5r3zarvary0c5xw7kv8f3t4', + 'tb1qxhkl607frtvjsy9nlyeg03lf6fsq947pl2pe82', + 'bc1p5d7rjq7g6rdk2yhzks9smlaqtedr4dekq08ge8ztwac72sfr9rusxg3297', + 'tb1pzpelffrdh9ptpaqnurwx30dlewqv57rcxfeetp86hsssk30p4cws38tr9y', ], invalid: [ + '3J98t1WpEZ73CNmQviecrnyiWrnqh0WNL0', + '3J98t1WpEZ73CNmQviecrnyiWrnqh0WNLo', + '3J98t1WpEZ73CNmQviecrnyiWrnqh0WNLI', + '3J98t1WpEZ73CNmQviecrnyiWrnqh0WNLl', '4J98t1WpEZ73CNmQviecrnyiWrnqRhWNLy', '0x56F0B8A998425c53c75C4A303D4eF987533c5597', 'pp8skudq3x5hzw8ew7vzsw8tn4k8wxsqsv0lt0mf3g', '17VZNX1SN5NlKa8UQFxwQbFeFc3iqRYhem', 'BC1QW508D6QEJXTDG4Y5R3ZARVAYR0C5XW7KV8F3T4', + 'bc1p5d7rjq7g6rdk2yhzks9smlaqtedr4dekq08ge8ztwac72sfr9rusxg3291', + 'bc1p5d7rjq7g6rdk2yhzks9smlaqtedr4dekq08ge8ztwac72sfr9rusxg329b', + 'bc1p5d7rjq7g6rdk2yhzks9smlaqtedr4dekq08ge8ztwac72sfr9rusxg329i', + 'bc1p5d7rjq7g6rdk2yhzks9smlaqtedr4dekq08ge8ztwac72sfr9rusxg329o', + 'BC1P5D7RJQ7G6RDK2YHZKS9SMLAQTEDR4DEKQ08GE8ZTWAC72SFR9RUSXG3297', + 'TB1PZPELFFRDH9PTPAQNURWX30DLEWQV57RCXFEETP86HSSSK30P4CWS38TR9Y', ], }); }); @@ -11333,6 +11967,28 @@ describe('Validators', () => { }); }); + it('should validate ISO 15924 script codes', () => { + test({ + validator: 'isISO15924', + valid: [ + 'Adlm', + 'Bass', + 'Copt', + 'Dsrt', + 'Egyd', + 'Latn', + 'Zzzz', + ], + invalid: [ + '', + 'arab', + 'zzzz', + 'Qaby', + 'Lati', + ], + }); + }); + it('should validate RFC 3339 dates', () => { test({ validator: 'isRFC3339', @@ -11425,6 +12081,37 @@ describe('Validators', () => { }); }); + it('should validate ISO 3166-1 numeric country codes', () => { + // from https://en.wikipedia.org/wiki/ISO_3166-1_numeric + test({ + validator: 'isISO31661Numeric', + valid: [ + '076', + '208', + '276', + '348', + '380', + '410', + '440', + '528', + '554', + '826', + ], + invalid: [ + '', + 'NL', + 'NLD', + '002', + '197', + '249', + '569', + '810', + '900', + '999', + ], + }); + }); + it('should validate ISO 4217 corrency codes', () => { // from https://en.wikipedia.org/wiki/ISO_4217 test({ @@ -11433,13 +12120,16 @@ describe('Validators', () => { 'AED', 'aed', 'AUD', - 'CUC', + 'CUP', 'EUR', 'GBP', 'LYD', 'MYR', 'SGD', + 'SLE', 'USD', + 'VED', + 'SLE', ], invalid: [ '', @@ -11451,6 +12141,8 @@ describe('Validators', () => { 'RWA', 'EURO', 'euro', + 'HRK', + 'CUC', ], }); }); @@ -11679,6 +12371,21 @@ describe('Validators', () => { 'Z1A 0B1', ], }, + { + locale: 'CO', + valid: [ + '050034', + '110221', + '441029', + '910001', + ], + invalid: [ + '11001', + '000000', + '109999', + '329999', + ], + }, { locale: 'ES', valid: [ @@ -11737,10 +12444,16 @@ describe('Validators', () => { locale: 'FR', valid: [ '75008', + '44522', + '38499', + '39940', + '01000', + ], + invalid: [ '44 522', - '98025', '38 499', - '39940', + '96000', + '98025', ], }, { @@ -11860,6 +12573,13 @@ describe('Validators', () => { '3950IO', '3997 GH', ], + invalid: [ + '1234', + '0603 JV', + '5194SA', + '9164 SD', + '1841SS', + ], }, { locale: 'NP', @@ -11956,6 +12676,9 @@ describe('Validators', () => { '39100-000', '22040-020', '39400-152', + '39100000', + '22040020', + '39400152', ], invalid: [ '79800A12', @@ -12282,6 +13005,55 @@ describe('Validators', () => { }); }); + it('should validate ISO6346 shipping container IDs with checksum digit 10 represented as 0', () => { + test({ + validator: 'isISO6346', + valid: [ + 'APZU3789870', + 'TEMU1002030', + 'DFSU1704420', + 'CMAU2221480', + 'SEGU5060260', + 'FCIU8939320', + 'TRHU3495670', + 'MEDU3871410', + 'CMAU2184010', + 'TCLU2265970', + ], + invalid: [ + 'APZU3789871', // Incorrect check digit + 'TEMU1002031', + 'DFSU1704421', + 'CMAU2221481', + 'SEGU5060261', + ], + }); + }); + it('should validate ISO6346 shipping container IDs with checksum digit 10 represented as 0', () => { + test({ + validator: 'isFreightContainerID', + valid: [ + 'APZU3789870', + 'TEMU1002030', + 'DFSU1704420', + 'CMAU2221480', + 'SEGU5060260', + 'FCIU8939320', + 'TRHU3495670', + 'MEDU3871410', + 'CMAU2184010', + 'TCLU2265970', + ], + invalid: [ + 'APZU3789871', // Incorrect check digit + 'TEMU1002031', + 'DFSU1704421', + 'CMAU2221481', + 'SEGU5060261', + ], + }); + }); + // EU-UK valid numbers sourced from https://ec.europa.eu/taxation_customs/tin/specs/FS-TIN%20Algorithms-Public.docx or constructed by @tplessas. it('should validate taxID', () => { test({ @@ -12827,6 +13599,19 @@ describe('Validators', () => { '19640823-32333', '1964082332333'], }); + test({ + validator: 'isTaxID', + args: ['uk-UA'], + valid: [ + '3006321856', + '3003102490', + '2164212906'], + invalid: [ + '2565975632', + '256597563287', + 'КС00123456', + '2896235845'], + }); test({ validator: 'isTaxID', valid: [ @@ -12892,6 +13677,7 @@ describe('Validators', () => { '+&DxJ=X7-4L8jRCD', 'etV*p%Nr6w&H%FeF', '£3.ndSau_7', + 'VaLIDWith\\Symb0l', ], invalid: [ '', @@ -12905,37 +13691,6 @@ describe('Validators', () => { }); }); - it('should validate base64URL', () => { - test({ - validator: 'isBase64', - args: [{ urlSafe: true }], - valid: [ - '', - 'bGFkaWVzIGFuZCBnZW50bGVtZW4sIHdlIGFyZSBmbG9hdGluZyBpbiBzcGFjZQ', - '1234', - 'bXVtLW5ldmVyLXByb3Vk', - 'PDw_Pz8-Pg', - 'VGhpcyBpcyBhbiBlbmNvZGVkIHN0cmluZw', - ], - invalid: [ - ' AA', - '\tAA', - '\rAA', - '\nAA', - '123=', - 'This+isa/bad+base64Url==', - '0K3RgtC+INC30LDQutC+0LTQuNGA0L7QstCw0L3QvdCw0Y8g0YHRgtGA0L7QutCw', - ], - error: [ - null, - undefined, - {}, - [], - 42, - ], - }); - }); - it('should validate date', () => { test({ validator: 'isDate', @@ -12944,6 +13699,7 @@ describe('Validators', () => { new Date([2014, 2, 15]), new Date('2014-03-15'), '2020/02/29', + '2020-02-19', ], invalid: [ '', @@ -12957,6 +13713,20 @@ describe('Validators', () => { '2019-02-29', // non-leap year '2020-04-31', // invalid date '2020/03-15', // mixed delimiter + '-2020-04-19', + '-2023/05/24', + 'abc-2023/05/24', + '2024', + '2024-', + '2024-05', + '2024-05-', + '2024-05-01-', + '2024-05-01-abc', + '2024/', + '2024/05', + '2024/05/', + '2024/05/01/', + '2024/05/01/abc', ], }); test({ @@ -12972,6 +13742,21 @@ describe('Validators', () => { '15/7/02', '15-7-02', '15-07/2002', + '2024', + '2024-', + '2024-05', + '2024-05-', + '2024-05-01-', + '2024-05-01-abc', + '2024/', + '2024/05', + '2024/05/', + '2024/05/01/', + '2024/05/01/abc', + '15/', + '15/07', + '15/07/', + '15/07/2024/', ], }); test({ @@ -12987,6 +13772,21 @@ describe('Validators', () => { '15/7/02', '15-7-02', '15-07/2002', + '2024', + '2024-', + '2024-05', + '2024-05-', + '2024-05-01-', + '2024-05-01-abc', + '2024/', + '2024/05', + '2024/05/', + '2024/05/01/', + '2024/05/01/abc', + '15/', + '15/07', + '15/07/', + '15/07/2024/', ], }); test({ @@ -13001,6 +13801,22 @@ describe('Validators', () => { '15-7-2002', '15/07-02', '30/04/--', + '2024', + '2024-', + '2024-05', + '2024-05-', + '2024-05-01-', + '2024-05-01-abc', + '2024/', + '2024/05', + '2024/05/', + '2024/05/01/', + '2024/05/01/abc', + '15/', + '15/07', + '15/07/', + '15/07/2024/', + '15/07/24/', ], }); test({ @@ -13016,6 +13832,16 @@ describe('Validators', () => { '15-7-02', '5/7-02', '3/4/aa', + '2024/', + '2024/05', + '2024/05/', + '2024/05/01/', + '2024/05/01/abc', + '15/', + '15/07', + '15/07/', + '15/07/2024/', + '15/07/24/', ], }); test({ @@ -13031,6 +13857,16 @@ describe('Validators', () => { '15/7/02', '15-7-02', '15-07/2002', + '2024/', + '2024/05', + '2024/05/', + '2024/05/01/', + '2024/05/01/abc', + '15/', + '15/07', + '15/07/', + '15/07/2024/', + '15/07/24/', ], }); test({ @@ -13049,6 +13885,20 @@ describe('Validators', () => { new Date(), new Date([2014, 2, 15]), new Date('2014-03-15'), + '-2020-04-19', + '-2023/05/24', + 'abc-2023/05/24', + '2024', + '2024-', + '2024-05', + '2024-05-', + '2024-05-01-', + '2024-05-01-abc', + '2024/', + '2024/05', + '2024/05/', + '2024/05/01/', + '2024/05/01/abc', ], }); test({ @@ -13074,6 +13924,21 @@ describe('Validators', () => { '2019/02/29', '2020/04/31', '2020/03-15', + '-2020-04-19', + '-2023/05/24', + 'abc-2023/05/24', + '2024', + '2024-', + '2024-05', + '2024-05-', + '2024-05-01-', + '2024-05-01-abc', + '2024/', + '2024/05', + '2024/05/', + '2024/05/01/', + '2024/05/01/abc', + '2024 05 01 abc', ], }); test({ @@ -13093,6 +13958,17 @@ describe('Validators', () => { new Date([2014, 2, 15]), new Date('2014-03-15'), '29.02.2020', + '02.29.2020.20', + '2024-', + '2024-05', + '2024-05-', + '2024-05-01', + '-2020-04-19', + '-2023/05/24', + 'abc-2023/05/24', + '04.05.2024.', + '04.05.2024.abc', + 'abc.04.05.2024', ], }); // emulating Pacific time zone offset & time @@ -13154,6 +14030,35 @@ describe('Validators', () => { '009:50:01', ], }); + test({ + validator: 'isTime', + args: [{ hourFormat: 'hour24', mode: 'withOptionalSeconds' }], + valid: [ + '23:59:59', + '00:00:00', + '9:50:01', + '00:00', + '23:59', + '9:00', + ], + invalid: [ + '', + null, + undefined, + 23, + '01:00:01 PM', + '13:00:', + '00', + '26', + '00;01', + '0 :09', + '59:59:59', + '24:00:00', + '00:59:60', + '99:99:99', + '009:50:01', + ], + }); test({ validator: 'isTime', args: [{ hourFormat: 'hour12' }], @@ -13213,6 +14118,38 @@ describe('Validators', () => { '009:50:01', ], }); + test({ + validator: 'isTime', + args: [{ hourFormat: 'hour12', mode: 'withOptionalSeconds' }], + valid: [ + '12:59:59 PM', + '2:34:45 AM', + '7:00:00 AM', + '12:59 PM', + '12:59 AM', + '01:00 PM', + '01:00 AM', + '7:00 AM', + ], + invalid: [ + '', + null, + undefined, + 23, + '01:00: 1 PM', + '13:00:', + '00', + '26', + '00;01', + '0 :09', + '59:59:59', + '24:00:00', + '00:59:60', + '99:99:99', + '9:50:01', + '009:50:01', + ], + }); }); it('should be valid license plate', () => { test({ @@ -13558,6 +14495,22 @@ describe('Validators', () => { ], invalid: ['mh04ad0045', 'invalidlicenseplate', '4578', '', 'GJ054GH4785'], }); + test({ + validator: 'isLicensePlate', + args: ['en-SG'], + valid: [ + 'SGX 1234 A', + 'SGX-1234-A', + 'SGB1234Z', + ], + invalid: [ + 'sg1234a', + 'invalidlicenseplate', + '4578', + '', + 'GJ054GH4785', + ], + }); }); it('should validate VAT numbers', () => { test({ @@ -13936,10 +14889,24 @@ describe('Validators', () => { validator: 'isVAT', args: ['AU'], valid: [ + 'AU53004085616', + '53004085616', + 'AU65613309809', + '65613309809', + 'AU34118972998', + '34118972998', + ], + invalid: [ + 'AU65613309808', + '65613309808', + 'AU55613309809', + '55613309809', + 'AU65613319809', + '65613319809', + 'AU34117972998', + '34117972998', 'AU12345678901', '12345678901', - ], - invalid: [ 'AU 12345678901', '1234567890', ], @@ -14022,11 +14989,11 @@ describe('Validators', () => { validator: 'isVAT', args: ['KZ'], valid: [ - 'KZ123456789', - '123456789', + 'KZ123456789012', + '123456789012', ], invalid: [ - 'KZ 123456789', + 'KZ 123456789012', '12345678', ], }); @@ -14498,7 +15465,7 @@ describe('Validators', () => { ], invalid: [ '', - 'somthing', + 'something', 'valid@gmail.com', 'mailto:?subject=okay&subject=444', 'mailto:?subject=something&wrong=888', diff --git a/test/validators/isAfter.test.js b/test/validators/isAfter.test.js index d771d9198..f0daf8a17 100644 --- a/test/validators/isAfter.test.js +++ b/test/validators/isAfter.test.js @@ -27,6 +27,21 @@ describe('isAfter', () => { args: [{ comparisonDate: 'invalid date' }], invalid: ['invalid date', '2015-09-17'], }); + test({ + validator: 'isAfter', + args: [], // will fall back to the current date + valid: ['2100-08-04', new Date(Date.now() + 86400000).toString()], + }); + test({ + validator: 'isAfter', + args: [undefined], // will fall back to the current date + valid: ['2100-08-04', new Date(Date.now() + 86400000).toString()], + }); + test({ + validator: 'isAfter', + args: [{ comparisonDate: undefined }], // will fall back to the current date + valid: ['2100-08-04', new Date(Date.now() + 86400000).toString()], + }); }); describe('(legacy syntax)', () => { diff --git a/test/validators/isBase64.test.js b/test/validators/isBase64.test.js new file mode 100644 index 000000000..c0074343a --- /dev/null +++ b/test/validators/isBase64.test.js @@ -0,0 +1,201 @@ +import { format } from 'util'; +import test from '../testFunctions'; +import validator from '../../src'; + +describe('isBase64', () => { + it('should validate base64 strings with default options', () => { + test({ + validator: 'isBase64', + valid: [ + '', + 'Zg==', + 'Zm8=', + 'Zm9v', + 'Zm9vYg==', + 'Zm9vYmE=', + 'Zm9vYmFy', + 'TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQsIGNvbnNlY3RldHVyIGFkaXBpc2NpbmcgZWxpdC4=', + 'Vml2YW11cyBmZXJtZW50dW0gc2VtcGVyIHBvcnRhLg==', + 'U3VzcGVuZGlzc2UgbGVjdHVzIGxlbw==', + 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuMPNS1Ufof9EW/M98FNw' + + 'UAKrwflsqVxaxQjBQnHQmiI7Vac40t8x7pIb8gLGV6wL7sBTJiPovJ0V7y7oc0Ye' + + 'rhKh0Rm4skP2z/jHwwZICgGzBvA0rH8xlhUiTvcwDCJ0kc+fh35hNt8srZQM4619' + + 'FTgB66Xmp4EtVyhpQV+t02g6NzK72oZI0vnAvqhpkxLeLiMCyrI416wHm5Tkukhx' + + 'QmcL2a6hNOyu0ixX/x2kSFXApEnVrJ+/IxGyfyw8kf4N2IZpW5nEP847lpfj0SZZ' + + 'Fwrd1mnfnDbYohX2zRptLy2ZUn06Qo9pkG5ntvFEPo9bfZeULtjYzIl6K8gJ2uGZ' + + 'HQIDAQAB', + ], + invalid: [ + '12345', + 'Vml2YW11cyBmZXJtZtesting123', + 'Zg=', + 'Z===', + 'Zm=8', + '=m9vYg==', + 'Zm9vYmFy====', + ], + }); + + test({ + validator: 'isBase64', + args: [{ urlSafe: true }], + valid: [ + '', + 'bGFkaWVzIGFuZCBnZW50bGVtZW4sIHdlIGFyZSBmbG9hdGluZyBpbiBzcGFjZQ', + '1234', + 'bXVtLW5ldmVyLXByb3Vk', + 'PDw_Pz8-Pg', + 'VGhpcyBpcyBhbiBlbmNvZGVkIHN0cmluZw', + ], + invalid: [ + ' AA', + '\tAA', + '\rAA', + '\nAA', + 'This+isa/bad+base64Url==', + '0K3RgtC+INC30LDQutC+0LTQuNGA0L7QstCw0L3QvdCw0Y8g0YHRgtGA0L7QutCw', + ], + error: [ + null, + undefined, + {}, + [], + 42, + ], + }); + + for (let i = 0, str = '', encoded; i < 1000; i++) { + str += String.fromCharCode(Math.random() * 26 | 97); // eslint-disable-line no-bitwise + encoded = Buffer.from(str).toString('base64'); + if (!validator.isBase64(encoded)) { + let msg = format('validator.isBase64() failed with "%s"', encoded); + throw new Error(msg); + } + } + }); + + it('should validate standard Base64 with padding', () => { + test({ + validator: 'isBase64', + args: [{ urlSafe: false, padding: true }], + valid: [ + '', + 'TWFu', + 'TWE=', + 'TQ==', + 'SGVsbG8=', + 'U29mdHdhcmU=', + 'YW55IGNhcm5hbCBwbGVhc3VyZS4=', + ], + invalid: [ + 'TWF', + 'TWE===', + 'SGVsbG8@', + 'SGVsbG8===', + 'SGVsb G8=', + '====', + ], + }); + }); + + it('should validate standard Base64 without padding', () => { + test({ + validator: 'isBase64', + args: [{ urlSafe: false, padding: false }], + valid: [ + '', + 'TWFu', + 'TWE', + 'TQ', + 'SGVsbG8', + 'U29mdHdhcmU', + 'YW55IGNhcm5hbCBwbGVhc3VyZS4', + ], + invalid: [ + 'TWE=', + 'TQ===', + 'SGVsbG8@', + 'SGVsbG8===', + 'SGVsb G8', + '====', + ], + }); + }); + + it('should validate Base64url with padding', () => { + test({ + validator: 'isBase64', + args: [{ urlSafe: true, padding: true }], + valid: [ + '', + 'SGVsbG8=', + 'U29mdHdhcmU=', + 'YW55IGNhcm5hbCBwbGVhc3VyZS4=', + 'SGVsbG8-', + 'SGVsbG8_', + ], + invalid: [ + 'SGVsbG8===', + 'SGVsbG8@', + 'SGVsb G8=', + '====', + ], + }); + }); + + it('should validate Base64url without padding', () => { + test({ + validator: 'isBase64', + args: [{ urlSafe: true, padding: false }], + valid: [ + '', + 'SGVsbG8', + 'U29mdHdhcmU', + 'YW55IGNhcm5hbCBwbGVhc3VyZS4', + 'SGVsbG8-', + 'SGVsbG8_', + ], + invalid: [ + 'SGVsbG8=', + 'SGVsbG8===', + 'SGVsbG8@', + 'SGVsb G8', + '====', + ], + }); + }); + + it('should handle mixed cases correctly', () => { + test({ + validator: 'isBase64', + args: [{ urlSafe: false, padding: true }], + valid: [ + '', + 'TWFu', + 'TWE=', + 'TQ==', + ], + invalid: [ + 'TWE', + 'TQ=', + 'TQ===', + ], + }); + + test({ + validator: 'isBase64', + args: [{ urlSafe: true, padding: false }], + valid: [ + '', + 'SGVsbG8', + 'SGVsbG8-', + 'SGVsbG8_', + ], + invalid: [ + 'SGVsbG8=', + 'SGVsbG8@', + 'SGVsb G8', + ], + }); + }); +}); diff --git a/test/validators/isBefore.test.js b/test/validators/isBefore.test.js new file mode 100644 index 000000000..298e5b410 --- /dev/null +++ b/test/validators/isBefore.test.js @@ -0,0 +1,119 @@ +import { describe } from 'mocha'; +import test from '../testFunctions'; + +describe('isBefore', () => { + describe('should validate dates a given end date', () => { + describe('new syntax', () => { + test({ + validator: 'isBefore', + args: [{ comparisonDate: '08/04/2011' }], + valid: ['2010-07-02', '2010-08-04', new Date(0).toString()], + invalid: ['08/04/2011', new Date(2011, 9, 10).toString()], + }); + test({ + validator: 'isBefore', + args: [{ comparisonDate: new Date(2011, 7, 4).toString() }], + valid: ['2010-07-02', '2010-08-04', new Date(0).toString()], + invalid: ['08/04/2011', new Date(2011, 9, 10).toString()], + }); + test({ + validator: 'isBefore', + args: [{ comparisonDate: '2011-08-03' }], + valid: ['1999-12-31'], + invalid: ['invalid date'], + }); + test({ + validator: 'isBefore', + args: [{ comparisonDate: 'invalid date' }], + invalid: ['invalid date', '1999-12-31'], + }); + }); + + describe('legacy syntax', () => { + test({ + validator: 'isBefore', + args: ['08/04/2011'], + valid: ['2010-07-02', '2010-08-04', new Date(0).toString()], + invalid: ['08/04/2011', new Date(2011, 9, 10).toString()], + }); + test({ + validator: 'isBefore', + args: [new Date(2011, 7, 4).toString()], + valid: ['2010-07-02', '2010-08-04', new Date(0).toString()], + invalid: ['08/04/2011', new Date(2011, 9, 10).toString()], + }); + test({ + validator: 'isBefore', + args: ['2011-08-03'], + valid: ['1999-12-31'], + invalid: ['invalid date'], + }); + test({ + validator: 'isBefore', + args: ['invalid date'], + invalid: ['invalid date', '1999-12-31'], + }); + }); + }); + + describe('should validate dates a default end date', () => { + describe('new syntax', () => { + test({ + validator: 'isBefore', + valid: [ + '2000-08-04', + new Date(0).toString(), + new Date(Date.now() - 86400000).toString(), + ], + invalid: ['2100-07-02', new Date(2217, 10, 10).toString()], + }); + test({ + validator: 'isBefore', + args: undefined, // will fall back to the current date + valid: ['1999-06-07'], + }); + test({ + validator: 'isBefore', + args: [], // will fall back to the current date + valid: ['1999-06-07'], + }); + test({ + validator: 'isBefore', + args: [undefined], // will fall back to the current date + valid: ['1999-06-07'], + }); + test({ + validator: 'isBefore', + args: [{ comparisonDate: undefined }], // will fall back to the current date + valid: ['1999-06-07'], + }); + }); + + describe('legacy syntax', () => { + test({ + validator: 'isBefore', + valid: [ + '2000-08-04', + new Date(0).toString(), + new Date(Date.now() - 86400000).toString(), + ], + invalid: ['2100-07-02', new Date(2217, 10, 10).toString()], + }); + test({ + validator: 'isBefore', + args: undefined, // will fall back to the current date + valid: ['1999-06-07'], + }); + test({ + validator: 'isBefore', + args: [], // will fall back to the current date + valid: ['1999-06-07'], + }); + test({ + validator: 'isBefore', + args: [undefined], // will fall back to the current date + valid: ['1999-06-07'], + }); + }); + }); +}); diff --git a/test/validators/isIP.test.js b/test/validators/isIP.test.js new file mode 100644 index 000000000..62ebbd112 --- /dev/null +++ b/test/validators/isIP.test.js @@ -0,0 +1,304 @@ +import test from '../testFunctions'; + +describe('isIP', () => { + it('should validate IP addresses', () => { + test({ + validator: 'isIP', + valid: [ + '127.0.0.1', + '0.0.0.0', + '255.255.255.255', + '1.2.3.4', + '::1', + '2001:db8:0000:1:1:1:1:1', + '2001:db8:3:4::192.0.2.33', + '2001:41d0:2:a141::1', + '::ffff:127.0.0.1', + '::0000', + '0000::', + '1::', + '1111:1:1:1:1:1:1:1', + 'fe80::a6db:30ff:fe98:e946', + '::', + '::8', + '::ffff:127.0.0.1', + '::ffff:255.255.255.255', + '::ffff:0:255.255.255.255', + '::2:3:4:5:6:7:8', + '::255.255.255.255', + '0:0:0:0:0:ffff:127.0.0.1', + '1:2:3:4:5:6:7::', + '1:2:3:4:5:6::8', + '1::7:8', + '1:2:3:4:5::7:8', + '1:2:3:4:5::8', + '1::6:7:8', + '1:2:3:4::6:7:8', + '1:2:3:4::8', + '1::5:6:7:8', + '1:2:3::5:6:7:8', + '1:2:3::8', + '1::4:5:6:7:8', + '1:2::4:5:6:7:8', + '1:2::8', + '1::3:4:5:6:7:8', + '1::8', + 'fe80::7:8%eth0', + 'fe80::7:8%1', + '64:ff9b::192.0.2.33', + '0:0:0:0:0:0:10.0.0.1', + ], + invalid: [ + 'abc', + '256.0.0.0', + '0.0.0.256', + '26.0.0.256', + '0200.200.200.200', + '200.0200.200.200', + '200.200.0200.200', + '200.200.200.0200', + '::banana', + 'banana::', + '::1banana', + '::1::', + '1:', + ':1', + ':1:1:1::2', + '1:1:1:1:1:1:1:1:1:1:1:1:1:1:1:1', + '::11111', + '11111:1:1:1:1:1:1:1', + '2001:db8:0000:1:1:1:1::1', + '0:0:0:0:0:0:ffff:127.0.0.1', + '0:0:0:0:ffff:127.0.0.1', + 'BC:e4d5:c:e7b9::%40i0nccymtl9cwfKo.5vaeXLSGRMe:EDh2qs5wkhnPws5xQKqafjfAMm6wGFCJ.bVFsZfb', + '1dC:0DF8:62D:3AC::%KTatXocjaFVioS0RTNQl4mA.V151o0RSy.JIu-D-D8.d3171ZWsSJ7PK4YjkJCRN0F', + ], + }); + + test({ + validator: 'isIP', + args: [{ version: 'invalid version' }], + valid: [], + invalid: [ + '127.0.0.1', + '0.0.0.0', + '255.255.255.255', + '1.2.3.4', + ], + }); + + test({ + validator: 'isIP', + args: [{ version: null }], + valid: [ + '127.0.0.1', + '0.0.0.0', + '255.255.255.255', + '1.2.3.4', + ], + }); + + test({ + validator: 'isIP', + args: [{ version: undefined }], + valid: [ + '127.0.0.1', + '0.0.0.0', + '255.255.255.255', + '1.2.3.4', + ], + }); + + test({ + validator: 'isIP', + args: [{ version: 4 }], + valid: [ + '127.0.0.1', + '0.0.0.0', + '255.255.255.255', + '1.2.3.4', + '255.0.0.1', + '0.0.1.1', + ], + invalid: [ + '::1', + '2001:db8:0000:1:1:1:1:1', + '::ffff:127.0.0.1', + '137.132.10.01', + '0.256.0.256', + '255.256.255.256', + ], + }); + + test({ + validator: 'isIP', + args: [{ version: 6 }], + valid: [ + '::1', + '2001:db8:0000:1:1:1:1:1', + '::ffff:127.0.0.1', + 'fe80::1234%1', + 'ff08::9abc%10', + 'ff08::9abc%interface10', + 'ff02::5678%pvc1.3', + ], + invalid: [ + '127.0.0.1', + '0.0.0.0', + '255.255.255.255', + '1.2.3.4', + '::ffff:287.0.0.1', + '%', + 'fe80::1234%', + 'fe80::1234%1%3%4', + 'fe80%fe80%', + ], + }); + + test({ + validator: 'isIP', + args: [{ version: 10 }], + valid: [], + invalid: [ + '127.0.0.1', + '0.0.0.0', + '255.255.255.255', + '1.2.3.4', + '::1', + '2001:db8:0000:1:1:1:1:1', + ], + }); + }); + + describe('legacy syntax', () => { + it('should validate IP addresses', () => { + test({ + validator: 'isIP', + valid: [ + '127.0.0.1', + '0.0.0.0', + '255.255.255.255', + '1.2.3.4', + '::1', + '2001:db8:0000:1:1:1:1:1', + '2001:db8:3:4::192.0.2.33', + '2001:41d0:2:a141::1', + '::ffff:127.0.0.1', + '::0000', + '0000::', + '1::', + '1111:1:1:1:1:1:1:1', + 'fe80::a6db:30ff:fe98:e946', + '::', + '::8', + '::ffff:127.0.0.1', + '::ffff:255.255.255.255', + '::ffff:0:255.255.255.255', + '::2:3:4:5:6:7:8', + '::255.255.255.255', + '0:0:0:0:0:ffff:127.0.0.1', + '1:2:3:4:5:6:7::', + '1:2:3:4:5:6::8', + '1::7:8', + '1:2:3:4:5::7:8', + '1:2:3:4:5::8', + '1::6:7:8', + '1:2:3:4::6:7:8', + '1:2:3:4::8', + '1::5:6:7:8', + '1:2:3::5:6:7:8', + '1:2:3::8', + '1::4:5:6:7:8', + '1:2::4:5:6:7:8', + '1:2::8', + '1::3:4:5:6:7:8', + '1::8', + 'fe80::7:8%eth0', + 'fe80::7:8%1', + '64:ff9b::192.0.2.33', + '0:0:0:0:0:0:10.0.0.1', + ], + invalid: [ + 'abc', + '256.0.0.0', + '0.0.0.256', + '26.0.0.256', + '0200.200.200.200', + '200.0200.200.200', + '200.200.0200.200', + '200.200.200.0200', + '::banana', + 'banana::', + '::1banana', + '::1::', + '1:', + ':1', + ':1:1:1::2', + '1:1:1:1:1:1:1:1:1:1:1:1:1:1:1:1', + '::11111', + '11111:1:1:1:1:1:1:1', + '2001:db8:0000:1:1:1:1::1', + '0:0:0:0:0:0:ffff:127.0.0.1', + '0:0:0:0:ffff:127.0.0.1', + ], + }); + test({ + validator: 'isIP', + args: [4], + valid: [ + '127.0.0.1', + '0.0.0.0', + '255.255.255.255', + '1.2.3.4', + '255.0.0.1', + '0.0.1.1', + ], + invalid: [ + '::1', + '2001:db8:0000:1:1:1:1:1', + '::ffff:127.0.0.1', + '137.132.10.01', + '0.256.0.256', + '255.256.255.256', + ], + }); + test({ + validator: 'isIP', + args: [6], + valid: [ + '::1', + '2001:db8:0000:1:1:1:1:1', + '::ffff:127.0.0.1', + 'fe80::1234%1', + 'ff08::9abc%10', + 'ff08::9abc%interface10', + 'ff02::5678%pvc1.3', + ], + invalid: [ + '127.0.0.1', + '0.0.0.0', + '255.255.255.255', + '1.2.3.4', + '::ffff:287.0.0.1', + '%', + 'fe80::1234%', + 'fe80::1234%1%3%4', + 'fe80%fe80%', + ], + }); + test({ + validator: 'isIP', + args: [10], + valid: [], + invalid: [ + '127.0.0.1', + '0.0.0.0', + '255.255.255.255', + '1.2.3.4', + '::1', + '2001:db8:0000:1:1:1:1:1', + ], + }); + }); + }); +});