Skip to content

Commit

Permalink
Beta version code
Browse files Browse the repository at this point in the history
  • Loading branch information
fwh1990 committed May 16, 2019
1 parent 3dd5f0f commit ad98c2d
Show file tree
Hide file tree
Showing 8 changed files with 1,395 additions and 0 deletions.
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
.idea/
*.log
node_modules/
build/
119 changes: 119 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
## 安装
```bash
yarn add antd-form-rules

# 或者

npm install antd-form-rules --save
```

## 使用

```javascript
import { FormRules } from 'antd-form-rules';

getFieldDecorator('id', {
rules: FormRules.withName('字段名').isRequired().create(),
});
```

## 方法介绍
#### withName(fileName: string)
规则必须先初始化才能做链式调用
```javascript
FormRules.withName('字段');
```

#### create()
生成的规则由该方法统一转换为antd需要的格式
```javascript
FormRules.withName('字段').create();
```

#### isRequired(onlyWhiteSpaceIsError = true)
通用方法,用于强调前一个规则是必填的,不能跳过。
```javascript
FormRules.withName('字段')
.string(1, 15).isRequired()
.match(/\w+/).isRequired()
.create();

FormRules.withName('字段').string().isRequired().create();
```

如果isRequired前面没有规则,那么会默认添加一个string()的规则
```javascript
FormRules.withName('字段').isRequired().create();
// 等于
FormRules.withName('字段').string().isRequired().create();
```

#### string(min?: number, max?: number, message?: string)
字符串规则,可自定义长度

```javascript
FormRules.withName('字段').string().create();
FormRules.withName('字段').string(1, 15).create();
FormRules.withName('字段').string(20).create();
FormRules.withName('字段').string(undefined, 20).create();
```

#### bool(message?: string)
布尔值规则,常用于Radio

#### array(message?: string)
数组规则

#### phone(message?: string)
国内11位手机号

#### number(min?: number, max?: number, message?: string)
数字,包括小数、整数、负数、正数

```javascript
FormRules.withName('字段').number().create();
FormRules.withName('字段').number(0.01, 1).create();
FormRules.withName('字段').number(0).create();
FormRules.withName('字段').number(undefined, 5).create();
```

#### integer(min?: number, max?: number, message?: string)
只能是整数

```javascript
FormRules.withName('字段').integer().create();
FormRules.withName('字段').integer(1).create();
FormRules.withName('字段').integer(1, 5).create();
FormRules.withName('字段').integer(undefined, 5).create();
```

#### email(message?: string)
邮箱号规则

#### match(pattern: RegExp, message?: string)
正则匹配
```javascript
FormRules.withName('字段').match(/\w\s*\w/).isRequired().create();
```

#### url(message?: string)
超链接规则

#### callback(fn: Function)
自定义规则

```javascript
FormRules.withName('字段').callback((value, field) => {
if (value !== '孙悟空') {
return new Error('这个是六耳猕猴');
}
}).create();
```

#### append(obj)
如果以上规则都不能满足你,那么可以用这个append直接添加antd的原生规则。或者欢迎issue
```javascript
import { FormRuleType } from 'antd-form-rules';

FormRules.withName('字段').string().append({ required: true, type: FormRuleType.object }).create();
```
15 changes: 15 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
{
"name": "antd-form-rules",
"version": "1.0.0",
"main": "index.js",
"types": "index.d.ts",
"repository": "[email protected]:fwh1990/antd-form-rules.git",
"author": "范文华 <[email protected]>",
"license": "MIT",
"peerDependencies": {
"antd": "*"
},
"devDependencies": {
"typescript": "^3.4.5"
}
}
28 changes: 28 additions & 0 deletions publish.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
#!/usr/bin/env bash

set -e

rm -rf ./build
node_modules/.bin/tsc
mv ./build/src/* ./build/
rm -r ./build/src
cp package.json README.md LICENSE ./build

old_registry=$(npm config get registry)
npm config set registry https://registry.npmjs.org
set +e
whoami=$(npm whoami 2>/dev/null)
set -e

if [ -z "$whoami" ]
then
echo "login plz..."
npm login
fi
echo "I am: $(npm whoami)"

sleep 1
echo "Begin publish..."
npm publish ./build/

npm config set registry ${old_registry}
16 changes: 16 additions & 0 deletions src/FormRuleType.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
export enum FormRuleType {
string = 'string',
number = 'number',
boolean = 'boolean',
method = 'method',
regexp = 'regexp',
integer = 'integer',
float = 'float',
array = 'array',
object = 'object',
enum = 'enum',
date = 'date',
url = 'url',
hex = 'hex',
email = 'email',
}
196 changes: 196 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,196 @@
import { ValidationRule } from 'antd/lib/form';
import { FormRuleType } from './FormRuleType';

export { FormRuleType } from './FormRuleType';

export class FormRules {
private readonly name: string;

private rules: ValidationRule[] = [];

constructor(name: string) {
this.name = name;
}

public static withName(fieldLocalName: string): FormRules {
return new FormRules(fieldLocalName);
}

private static formatMessageByLimit(min?: number, max?: number, type: string = '', unit: string = '') {
const existMin = typeof min === 'number';
const existMax = typeof max === 'number';
let message: string;

if (existMax && existMin) {
message = `:name必须是${type},且${unit}在:min到:max之间`;
} else if (existMax) {
message = `:name必须是${type},且${unit}小于等于:max`;
} else if (existMin) {
message = `:name是必须是${type},且${unit}大于等于:min`;
} else {
message = `:name必须是${type}`;
}

if (existMin) {
message = message.replace(':min', String(min));
}

if (existMax) {
message = message.replace(':max', String(max));
}

return message;
}

// 验证时转换数字类型(但是并不影响最终值)
private static transformNumber(value?: string | number): number | undefined {
if (typeof value === 'number') {
return value;
}

return typeof value === 'string' && value.length ? Number(value) : void 0;
}

public isRequired(onlyWhiteSpaceIsError = true): FormRules {
let lastRule = this.rules[this.rules.length - 1];

if (!lastRule) {
this.string();
lastRule = this.rules[this.rules.length - 1];
}

lastRule.required = true;
lastRule.whitespace = onlyWhiteSpaceIsError;

return this;
}

public append(obj: ValidationRule): FormRules {
const cloneObj = { ...obj };

if (typeof cloneObj.message === 'string') {
cloneObj.message = cloneObj.message.replace(':name', this.name);
}

this.rules.push(cloneObj);

return this;
}

public string(min?: number, max?: number, message: string = ''): FormRules {
message = message || FormRules.formatMessageByLimit(min, max, '字符串', '长度');

this.rules.push({
type: FormRuleType.string,
min,
max,
message: message.replace(':name', this.name),
});

return this;
}

public bool(message: string = ':name必须是布尔值'): FormRules {
this.rules.push({
type: FormRuleType.boolean,
message: message.replace(':name', this.name),
});

return this;
}

public array(message: string = ':name必须是数组'): FormRules {
this.rules.push({
type: FormRuleType.array,
message: message.replace(':name', this.name),
});

return this;
}

public phone(message = '请输入正确的:name'): FormRules {
this.rules.push({
type: FormRuleType.string,
pattern: /^1[3-9]\d{9}$/u,
message: message.replace(':name', this.name),
});

return this;
}

public number(min?: number, max?: number, message: string = ''): FormRules {
message = message || FormRules.formatMessageByLimit(min, max, '数字', '值');

this.rules.push({
type: FormRuleType.number,
transform: FormRules.transformNumber,
min,
max,
message: message.replace(':name', this.name),
});

return this;
}

public integer(min?: number, max?: number, message = '') {
message = message || FormRules.formatMessageByLimit(min, max, '整数', '值');

this.rules.push({
type: FormRuleType.integer,
transform: FormRules.transformNumber,
min,
max,
message: message.replace(':name', this.name),
});

return this;
}

public email(message = ':name必须是个邮箱号') {
this.rules.push({
type: FormRuleType.email,
message: message.replace(':name', this.name),
});

return this;
}

public match(pattern: RegExp, message = ':name不符合匹配标准') {
this.rules.push({
type: FormRuleType.string,
pattern,
message: message.replace(':name', this.name),
});

return this;
}

public url(message = ':name不符合url规则') {
this.rules.push({
type: FormRuleType.url,
message: message.replace(':name', this.name),
});

return this;
}

public callback<T extends Error>(func: (value: any, field: string) => T | T[] | void) {
this.rules.push({
validator: (rule, value, callback) => {
const errors: T | T[] | void = func(value, rule.field);

callback(Array.isArray(errors) ? errors : [errors]);
},
});

return this;
}

public create(): ValidationRule[] {
const rules = this.rules;

this.rules = [];

return rules;
}
}
Loading

0 comments on commit ad98c2d

Please sign in to comment.