{"id":13671387,"url":"https://github.com/huruji/no-validate","last_synced_at":"2025-04-10T16:12:17.736Z","repository":{"id":97310115,"uuid":"155223779","full_name":"huruji/no-validate","owner":"huruji","description":"使用Proxy实现的优雅、流畅的校验系统","archived":false,"fork":false,"pushed_at":"2018-11-22T13:12:13.000Z","size":137,"stargazers_count":6,"open_issues_count":0,"forks_count":0,"subscribers_count":2,"default_branch":"master","last_synced_at":"2025-03-24T14:01:37.392Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/huruji.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2018-10-29T14:16:21.000Z","updated_at":"2019-05-22T02:30:33.000Z","dependencies_parsed_at":null,"dependency_job_id":"469bdd1e-439b-4367-8a86-40932e6719b2","html_url":"https://github.com/huruji/no-validate","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/huruji%2Fno-validate","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/huruji%2Fno-validate/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/huruji%2Fno-validate/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/huruji%2Fno-validate/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/huruji","download_url":"https://codeload.github.com/huruji/no-validate/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248251109,"owners_count":21072685,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-08-02T09:01:08.178Z","updated_at":"2025-04-10T16:12:17.717Z","avatar_url":"https://github.com/huruji.png","language":"JavaScript","readme":"\u003cp align=\"center\"\u003e\n  \u003cimg height=\"150\" src=\"./logo.png\"/\u003e\n\u003c/p\u003e\n\n# noV\n\n使用**Proxy**实现的优雅的、流畅的校验系统，目前已应用在**百万DAU**的线上产品中。\n\n## 安装\n\n```bash\nnpm install --dev-save no-validate\n```\n\n## 使用\n\n```js\nimport noV from 'no-validate';\n\nnoV().maxLength().test(myValue);\n```\n\n验证表单最常见的邮箱、手机号码：\n\n```js\nnoV().email().test(myEmail);\n\nnoV().phoneNumber().test(myPhone);\n```\n\n或许你还想要验证用户设置的密码是否符合你的规则，假设我们规定密码的规则是长度为至少为6位，并且至少包含数字和字母\n那么我们可以使用类似链式一样的操作（但是实际上，只有我们调用了test方法后，校验阶段才会开始）\n```js\nnoV().minLength(6).pattern(/[a-z]?[0-9]+[a-z]+/i).test(password)\n```\n\n\n或许有时候你还想取反其中的某个验证规则，这个时候你可以使用 `not` 这个修饰符：\n\n```js\nnoV().not.range(5,7).test(myStr)\n```\n\n这个时候意味着 `myStr` 的长度小于5或者大于7才会返回 `true`。\n\n**这当然还不够**\n\n如果你想要知道校验失败时具体是哪条规则没有通过，你可以使用 `testPlus` 方法，这个方法将会返回一个对象，包含result与step字段的对象\n\n假如我们规定标题长度需要大于4个字符，并且最后必须要以问号结尾，我们可以使用 `testPlus` 方法来精确了解到我们的校验规则具体的执行结果：\n\n```\nconst result = noV().minLength(5).pattern(/(\\?|？)$/).testPlus(myTitle)\n```\n\n如果 `myTitle` 在第二个校验规则失败了，那么这个 `result` 对象将会是：\n\n```js\n{\n  result: false,\n  step: 2\n}\n```\n\n有了这个信息我们可以很方便地针对每一个校验失败进行特定的处理，最常见的就是告诉用户需要怎样修改：\n```js\nconst errors = [\n  '请最少输入5个字符',\n  '标题须以问号结尾'\n]\n\nmodal.show(errors[result.step -1]);\n```\n\n为了更加方便一点，noV允许将这些额外的信息作为第二个参数传递给 `testPlus` 方法，如：\n```js\nconst result = noV().minLength(6).pattern(/[a-z]?[0-9]+[a-z]+/i).testplus(password, errors)\n```\n这样，result对象将会把这些额外的信息作为 `info` 字段的值：\n\n```js\n{\n  result: false,\n  step: 2,\n  info: '标题须以问号结尾'\n}\n```\n\n我们需要知道的是，传递给 `testPlus` 方法的额外信息不仅仅可以数组，还可以是一个以 **规则名** 为key的对象，上面的等价于：\n\n```js\nconst errors = {\n  minLength: '请最少输入5个字符',\n  pattern: '标题须以问号结尾'\n};\n\nconst result = noV().minLength(6).pattern(/[a-z]?[0-9]+[a-z]+/i).test(password, errors)\n```\n\n这样，如果你的校验规则需要经常修改，那么你也不会那么被动。\n\n鉴于笔者目前的工作以及前端多端环境的复杂，nov 还提供了对于UA校验的规则，包括对 `Android` 、 `IOS` 、 微信、QQ环境的校验，这通常在你的应用需要对不同环境适配（如果你的应用使用了微信、或者QQ的js-SDK，这将非常有用），例如：\n\n```js\nnoV().uaIOS().test(navigator.userAgent);\n\nnoV().uaAndroid().test(navigator.userAgent);\n\nnoV().uaWX().test(navigator.userAgent);\n\nnoV().uaQQ().test(navigator.userAgent)\n```\n\n## API\n\n### 规则（Rule）\n\n#### Type\n|               |                                                   | 例子                                  |\n| ------------- | ------------------------------------------------- | ------------------------------------- |\n| **number()**  | 类型为数字                                        | `noV().number().test(6)`              |\n| **array()**   | 类型为数组                                        | `noV().array().test(['n', 'o', 'V'])` |\n| **string()**  | 类型为字符串                                      | `noV().string().test('nov')`          |\n| **boolean()** | 类型为布尔值                                      | `noV().boolean().test(true)`          |\n| **float()**   | 类型为小数                                        | `noV().float().test(1.2)`             |\n| **nan()**     | 值是NaN                                           | `noV().nan().test(NaN)`               |\n| **null()**    | 值是null                                          | `noV().null().test(null)`             |\n| **object()**  | 类型是对象object                                  | `noV().object().test(new Date())`     |\n| **type(ty)**  | 精确校验类型（内部使用Object.prototype.toString） | `noV().type('RegExp').test(/^\\d+$/)`  |\n\n#### Number\n|                     |            | 例子                         |\n| ------------------- | ---------- | ---------------------------- |\n| **exact(value)**    | 全等       | `noV().exact(6).test(6)`     |\n| **equal(value)**    | 等于       | `noV().equal(1).test(1)`     |\n| **gt(value)**       | 大于       | `noV().gt(6).test(7)`        |\n| **gte(value)**      | 大于或等于 | `noV().gte(6).test(6)`       |\n| **lt(value)**       | 小于       | `noV().lt(6).test(5)`        |\n| **te(value)**       | 小于或等于 | `noV().lte(6).test(6)`       |\n| **ne(value)**       | 不等于     | `noV().ne(6).test(6)`        |\n| **range(min, max)** | 规定范围内 | `noV().range(2, 10).test(6)` |\n| **even()**          | 偶数       | `noV().even().test(4)`       |\n| **odd()**           | 奇数       | `noV().odd().test(3)`        |\n| **negative()**      | 负数       | `noV().negative().test(-3)`  |\n| **positive()**      | 正数       | `noV().positive().test(3)`   |\n\n#### String\n|                      |                                                | 例子                                          |\n| -------------------- | ---------------------------------------------- | --------------------------------------------- |\n| **exact(value)**     | 全等                                           | `noV().exact('nov').test('nov')`              |\n| **equal(value)**     | 等于                                           | `noV().equal('nov').test('nov')`              |\n| **length(min, max)** | 字符串长度范围                                 | `noV().length(1, 5).test('noV')`              |\n| **minLength(value)** | 字符串长度最小值                               | `noV().minLength(2).test('noV')`              |\n| **maxLength(value)** | 字符串长度最大值                               | `noV().maxLength(6).test('noV')`              |\n| **first(value)**     | 字符串第一个字符                               | `noV().first('n').test('noV')`                |\n| **end(value)**       | 字符串最后一个字符                             | `noV().end('V').test('noV')`                  |\n| **startWith(value)** | 字符串开头                                     | `noV().startWith('n').test('noV test')`       |\n| **endWith(value)**   | 字符串结尾                                     | `noV().endWith('t').test('noV test')`         |\n| **pattern(value)**   | 正则模式匹配                                   | `noV().pattern(/^\\d+$/).test('123123321')`    |\n| **lower()**          | 字符串全为小写                                 | `noV().lower().test(‘nov’)`                 |\n| **upper()**          | 字符串全为大写                                 | `noV().upper().test('NOV')`                   |\n| **email()**          | 字符串为email地址                              | `noV().email().test('huruji3@foxmail.com')`   |\n| **phoneNumber()**    | 字符串为手机号码                               | `noV().phoneNumber().test(phoneNumber)`       |\n| **url()**            | 字符串为url地址                                | `noV().url().test('http://google.com')`       |\n| **base64()**         | 字符串为base64字符串                           | `noV().base().test(base64Str)`                |\n| **uaIOS()**          | 浏览器ua为IOS系统(需要传递UA字符串)            | `noV().uaIOS().test(navigator.userAgent)`     |\n| **uaAndroid()**      | 浏览器ua为IOS系统(需要传递UA字符串)            | `noV().uaAndroid().test(navigator.userAgent)` |\n| **uaWX()**           | 浏览器ua在微信环境(需要传递UA字符串)           | `noV().uaWX().test(navigator.userAgent)`      |\n| **uaQQ()**           | 浏览器ua在QQ环境(需要传递UA字符串)             | `noV().uaQQ().test(navigator.userAgent)`      |\n| **json()**           | 字符串是json字符串（可用JSON.parse()方法解析） | `noV().json().test('{}')`                     |\n| **empty()**          | 字符串为空字符串                               | `noV().empty().test('noV')`                   |\n\n#### Array\n\n|                      |                      | 例子                                         |\n| -------------------- | -------------------- | -------------------------------------------- |\n| **length(min, max)** | 数组长度范围         | `noV().length(1, 5).test([1, 2, 3])`         |\n| **minLength(value)** | 数组长度最小值       | `noV().minLength(2).test([1, 2, 3])`         |\n| **maxLength(value)** | 数组长度最大值       | `noV().maxLength(6).test([1, 2, 3])`         |\n| **first(value)**     | 数组第一个元素       | `noV().first('n').test(['n', 'o', 'V'])`     |\n| **end(value)**       | 数组最后一个元素     | `noV().end('V').teest(['n', 'o', 'V'])`      |\n| **startWith(value)** | 数组第一个元素       | `noV().startWith('n').test(['n', 'o', 'V'])` |\n| **endWith(value)**   | 数组最后一个元素     | `noV().endWith('t').test(['n', 'o', 'V'])`   |\n| **unique()**         | 数组元素是否唯一     | `noV().unique().test([1, 2, 3, 1])`          |\n| **contains(search)** | 数组中是否包含某元素 | `noV().contains(2).test([1, 2, 3])`          |\n| **empty()**          | 数组为空数组         | `noV().empty().test([])`                     |\n\n\n#### \n\n#### Object\n|                                    |                                                                                                                    | 例子                                                     |\n| ---------------------------------- | ------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------- |\n| **empty()**                        | 对象为空对象                                                                                                       | `noV().empty().test([1, 2, 3])`                          |\n| **falsyObj(value)**                | 对象的键值是否全为falsy的值，其中value可指定为对象中的某些值为默认值，**这在校验你的对象是否被修改的时候非常有用** | `oV().falsyObj({'a.b': 2}).test({a: {b: 2,c: null}})`    |\n| **required([value], [value],...)** | 指定某些键是必须的                                                                                                 | `oV().required('name', 'age').test({a: {b: 2,c: null}})` |\n### 修饰符\n|            |                                                       | 例子                                              |\n| ---------- | ----------------------------------------------------- | ------------------------------------------------- |\n| **.not**   | 对接下来的规则取反                                    | `noV().not.email().test(‘huruji#gmail.com’)`    |\n| **.some**  | 对接下来的规则使用some（有符合规则的数据则返回true）  | `noV().some.minLength(2).test(['nov', 'v', 'v'])` |\n| **.every** | 对接下来的规则使用every（所有数据符合规则则返回true） | `noV().every.gt(6).test([1, 2, 3, 8])`            |\n\n### 校验\n|                                    |                                                                                                          | 例子                                                                                                                          |\n| ---------------------------------- | -------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------- |\n| **test(value)**                    | 对value按照rules顺序进行校验，遇到校验不通过将终止校验，返回一个布尔值                                   | `noV().gt(6).test(7)`                                                                                                         |\n| **testAll(value)**                 | 按rules顺序校验，遇到不通过不终止，返回一个由布尔值组成的数组                                            | `noV().minLength(2).startWith('n')test('noV')`                                                                                |\n| **testPlus(value [,infoOptions])** | 校验rules的结果并返回一个由 `step` 和 `result` 字段组成的对象，同时可通过 `infoOptions` 设置额外的信息， | `noV().minLength(1).maxLength(3).firs('n').testPlus('noVs', {minLength: 'mingLength',maxLength: 'maxLength',first: 'first'})` |","funding_links":[],"categories":["JavaScript"],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fhuruji%2Fno-validate","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fhuruji%2Fno-validate","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fhuruji%2Fno-validate/lists"}