17.0.0 • Published 3 months ago

@bigbear713/nb-form v17.0.0

Weekly downloads
-
License
MIT
Repository
github
Last release
3 months ago

@bigbear713/nb-form

Angular common form lib by bigBear713.

OnlineDemo

Bug Report

Feature Request

Document


Changelog


Feature

  • 提供常用的表单控件校验器:arrLength, equal, fileSize, fileType, required, whitespace。具体见下方校验器的定义;
  • 支持通过DI设置common error info;
  • 支持组件的更新策略为ChangeDetectionStrategy.OnPush
  • 支持在standalone component中使用;
  • 支持以standalone component的方式引入;

Version

nb-form的大版本和Angular的大版本保持对应关系
@bigbear713/nb-form@angular/core
^12.0.0^12.0.0
^13.0.0^13.0.0
^14.0.0^14.0.0
^15.0.0^15.0.0
^16.0.0^16.0.0
^17.0.0^17.0.0

Installation

$ npm i @bigbear713/nb-form
// or
$ yarn add @bigbear713/nb-form

API

Module

NbFormModule

表单模块。引入该模块后,可使用componentservicevalidators不需要引入该模块也可使用。

NbFormTestingModule

表单测试模块。用于Unit Test。

Validators

NbFormValidators.arrLength

v12.0.0
数组长度校验器
Params
NameTypeMandatoryDescriptionVersion
arrLength{ max?: number; min?: number }true数组长度限制。可单独设置最大或者最小长度。v12.0.0
Return
TypeDescription
{ [NbControlErrType.ARR_MAX_LENGTH]?: true;[NbControlErrType.ARR_MIN_LENGTH]?: true; }|null返回null表示符合条件,或者要校验的内容不是一个数组。返回{ [NbControlErrType.ARR_MAX_LENGTH]: true }表示数组长度超出最大长度限制。返回{ [NbControlErrType.ARR_MIN_LENGTH]: true }表示数组长度小于最小长度限制。
Usage
const maxControl = new FormArray([1,2,3,4,5,6],[NbFormValidators.arrLength({max:5,min:3})]);
console.log(maxControl.errors); // { [NbControlErrType.ARR_MAX_LENGTH]: true }

const minControl = new FormArray([1,2],[NbFormValidators.arrLength({max:5,min:3})]);
console.log(minControl.errors); // { [NbControlErrType.ARR_MIN_LENGTH]: true }

NbFormValidators.equal

v12.0.0
值是否相等校验器。当两个控件的值不相等时,当前控件会带有相关的错误信息。如果想两个控件都带有错误信息,可参考demo
Params
NameTypeMandatoryDescriptionVersion
comparedAbstractControltrue要对比的表单控件.v12.0.0
immediatelybooleanfalse是否立即校验。如果设置为false,则会在compared控件为dirty状态时才会校验。默认为truev12.1.0
Return
TypeDescription
{ [NbControlErrType.NOT_EQUAL]: true; }|null校验结果。返回null表示两个表单控件的值相等。返回{ [NbControlErrType.NOT_EQUAL]: true }表示两个表单控件值不相等。
Usage
const targetControl = new FormControl('');
const compareControl = new FormControl(null);
targetControl.setValidators([NbFormValidators.equal(compareControl)]);
console.log(targetControl.errors); // { [NbControlErrType.NOT_EQUAL]: true; }


const targetControl = new FormControl('');
const compareControl = new FormControl(null);
targetControl.setValidators([NbFormValidators.equal(compareControl,false)]);
console.log(targetControl.errors); // null

compareControl.markAsDirty();
targetControl.updateValueAndValidity();
console.log(targetControl.errors); // { [NbControlErrType.NOT_EQUAL]: true; }

NbFormValidators.fileSize

v12.0.0
文件大小校验器
Params
NameTypeMandatoryDescriptionVersion
fileSize{ max?: number; min?: number }true文件大小限制。可单独设置最大值或者最小值。最大最小值的单位是B.v12.0.0
Return
TypeDescription
{ [NbControlErrType.FILE_MAX_SIZE]?: true;[NbControlErrType.FILE_MIN_SIZE]?: true; }|null校验结果。返回null表示符合条件,或者要校验的内容不是一个File类型。返回{ [NbControlErrType.FILE_MAX_SIZE]: true }表示文件大小超出最大值限制。返回{ [NbControlErrType.FILE_MIN_SIZE]: true }表示文件大小小于最小值限制。
Usage
const control = new FormControl(new File(),[NbFormValidators.fileSize({max:5,min:3})]);
console.log(control.errors); // { [NbControlErrType.FILE_MAX_SIZE]: true; } / { [NbControlErrType.FILE_MIN_SIZE]?: true; }

NbFormValidators.fileType

v12.0.0
文件类型校验器
Params
NameTypeMandatoryDescriptionVersion
typesstring[]true要支持的文件类型,值应该为MIME Type.v12.0.0
Return
TypeDescription
{ [NbControlErrType.FILE_TYPE]: true; }|null校验结果。返回null表示符合条件,或者要校验的内容不是一个File类型。返回{ [NbControlErrType.FILE_TYPE]: true }表示文件类型不在要支持的类型中。
Usage
const control = new FormControl(new File(),[NbFormValidators.fileType(['image/jpeg','image/png'])]);
console.log(control.errors); // { [NbControlErrType.FILE_TYPE]: true; }

NbFormValidators.required

v12.0.0
必填校验器
Params
NameTypeMandatoryDescriptionVersion
requiredbooleanfalse表单控件是否必填。默认为true. 如果为true,则会调用Validators.required, 否则不会对表单控件内容做必填校验v12.0.0
Return
TypeDescription
{ [NbControlErrType.REQUIRED]: true; }|null校验结果。返回null表示符合条件。返回{ [NbControlErrType.REQUIRED]: true }表示表单控件不符合必填校验
Usage
const control = new FormControl('',[NbFormValidators.required(true)])
console.log(control.errors); // { [NbControlErrType.REQUIRED]: true; }

NbFormValidators.whitespace

v12.0.0
是否允许都为空格校验器
Params
NameTypeMandatoryDescriptionVersion
canWhitespacebooleanfalse表单控件可以都是空格内容。默认为true. 如果为true, 则允许控件值都是空格.v12.0.0
Return
TypeDescription
{ [NbControlErrType.WHITESPACE]: true; }|null校验结果。返回null表示符合条件。返回{ [NbControlErrType.WHITESPACE]: true }表示不允许都是空格的情况下,表单控件值都是空格
Usage
const control =new FormControl('    ',[NbFormValidators.whitespace(false)])
console.log(control.errors); // { [NbControlErrType.WHITESPACE]: true; }

Services

NbFormService

v12.0.0
提供常用表单功能的service
Methods
NameReturnDescriptionScenesVersion
getValidatorsFromControlConfig(config: INbControlConfig)ValidatorFn[]根据配置信息,获取校验器数组。可配置的条件有:required,max,min,maxLength,minLength,arrMaxLength,arrMinLength,maxFileSize,minFileSize,fileType,pattern,whitespace。其中max,min,maxLength,minLength,pattern等返回的是Validators提供的校验器。剩下的则为NbFormValidators提供的校验器需要根据配置信息快速设置校验器数组时v12.0.0
markAllAsDirty(control: NbAbstractControl, opts?: { onlySelf?: boolean; emitEvent?: boolean; })void将表单控件以及子控件都标记为dirty。control为要标记的控件,opts会在标记时,传给控件以及每个子控件适合想将一个控件以及自控件都标记为dirty的场景v12.0.0
showAllErrInfo(control: NbAbstractControl, opts?: { onlySelf?: boolean; emitEvent?: boolean; })void展示控件以及子控件的所有错误信息。通过调用control.markAllAsTouched,markAllAsDirty,updateAllValueAndValidity等常用方法,让错误信息在UI上展示出来。control为要操作的控件,opts会在调用markAllAsDirty,updateAllValueAndValidity时,传给控件以及每个子控件适合想将控件以及子控件的错误信息都展示给用户的场景,比如表单提交时。v12.0.0
updateAllValueAndValidity(control: NbAbstractControl, opts?: { onlySelf?: boolean; emitEvent?: boolean; })void将表单控件以及子控件都更新值和值的有效性。control为要操作的控件,opts会在操作时,传给控件以及每个子控件适合想让控件和子控件都更新值和值的有效性的场景v12.0.0
updateEqualControlsValidities(controls: { target: AbstractControl; compared: AbstractControl }, destroy$?: Subject)Subscription更新两个想相等的控件的有效性。只有当前后两次某个控件的状态改变时才会触发。这是一个订阅事件,返回值为订阅事件的索引。可通过它来取消事件的订阅。或者传入一个destroy$参数,在需要的时候通过destroy$发送值来取消订阅适合结合NbFormValidators.equal校验器,及时更新两个控件是否相等的状态,比如更改密码时的新密码和重复密码的验证v12.1.0
Usage
constructor(private formService: NbFormService) {}

const config:INbControlConfig={required:true,whitespace:false};
const validators = this.formService.getValidatorsFromControlConfig(config);
new FormControl('',validators);


const form = new FormGroup({
  // ...
});
this.markAllAsDirty(form,{onlySelf:true});


const form = new FormGroup({
  // ...
});
this.showAllErrInfo(form,{onlySelf:true});


const form = new FormGroup({
  // ...
});
this.updateAllValueAndValidity(form,{onlySelf:true});

const passwordControl = new FormControl();
const repeatPasswordControl = new FormControl();
passwordControl.setValidators([NbFormValidators.equal(repeatPasswordControl,false)]);
repeatPasswordControl.setValidators([NbFormValidators.equal(passwordControl,false)]);
const controls = {target:passwordControl,compared:repeatPasswordControl};
// 通过返回值取消订阅
const subscription = this.updateEqualControlsValidities(controls);
subscription.unsubscribe();
// 通过destroy$取消订阅
const destroy$ = new Subject<void>();
this.updateEqualControlsValidities(controls,destroy$);
destroy$.next();
destroy$.complete();

Components

<nb-control-err></nb-control-err>

v12.0.0
v15.1.0开始为standalone component
显示控件错误信息时使用的组件。错误信息支持stringObservable<string>, 以便适合多语言场景。可在providers中设置常用的错误信息,和单独传入该组件的错误信息将合并成最终使用的错误信息
Input
NameTypeMandatoryDefaultDescriptionVersion
controlAbstractControltrue-要显示的错误信息所属的控件。从v16.0.0开始,为必需属性v12.0.0
errInfoINbControlErrInfofalse{}当前控件的错误信息,会和providers中设置常用的错误信息一起组合成最终使用的错误信息。如果不传,则只会显示providers中设置常用的错误信息v12.0.0
Usage
<!-- control = new FormControl() -->
<!-- errInfo = {required:'这个字段必填!'} -->
<nb-control-err [control]="control" [errInfo]="errInfo" />

<!-- If the control is missing, an error will be reported -->
<nb-control-err [errInfo]="errInfo" />
// v15.1.0新增
// 在NgModule中引入
@NgModule({
  imports:[NbControlErrComponent],
  // ...
})
export class XXXModule{}

// 在standalone component中引入
@Component({
  standalone:true,
  imports:[NbControlErrComponent],
  // ...
})
export class XXXComponent{}

<nb-field-item></nb-field-item>

v12.0.0
v15.1.0开始为standalone component
字段项组件,常用于表单中。提供常见的字段布局,以及错误信息的展示
[field-label]
字段标签
Input
NameTypeMandatoryDefaultDescriptionVersion
controlAbstractControl | undefinedfalse-要显示错误信息的控件。v12.0.0
errInfoINbControlErrInfofalse{}要显示的错误信息。如果不传,则只会显示providers中设置常用的错误信息v12.0.0
requiredbooleanfalsefalse该字段是否必填。如果必填,字段标签左侧会出现一个"*"。默认为falsev12.0.0
Usage
<!-- 设置字段标签和字段内容,非必填,不显示错误信息 -->
<nb-field-item>
  <ng-container field-label>field 1</ng-container>
  <input>
</nb-field-item>

<!-- 必填,显示错误信息 -->
<nb-field-item [required]="true" [control]="control" [errInfo]="errInfo">
  <ng-container field-label>field 2</ng-container>
  <input>
</nb-field-item>
// v15.1.0新增
// 在NgModule中引入
@NgModule({
  imports:[NbFieldItemComponent],
  // ...
})
export class XXXModule{}

// 在standalone component中引入
@Component({
  standalone:true,
  imports:[NbFieldItemComponent],
  // ...
})
export class XXXComponent{}

Tokens

NB_CONTROL_COMMON_ERR_INFO

INbControlErrInfo
v15.0.0

NB_CONTROL_COMMON_ERR_INFO_TOKEN

INbControlErrInfo
v12.0.0, 从v15.0.0开始为@deprecated
用于设置常见的错误信息,避免每个地方都需要设置一遍。设置后,会和每个<nb-control-err></nb-control-err>组件中传入的错误信息组合成最终的错误信息。
Usage
  providers: [
    // ...
    {
      provide: NB_CONTROL_COMMON_ERR_INFO,
      useFactory: (transService: NbTransService) => ({
        [NbControlErrType.FILE_TYPE]: transService.translationAsync('fileType'),
        [NbControlErrType.FILE_MIN_SIZE]: 'The file min file is 50KB!',
      }),
      deps: [NbTransService]
    },
    // ...
  ]

Interfaces

NbAbstractControl

v12.0.0
抽象控件类型,包含AbstractControl, null, undefined 等3种类型

INbControlConfig

v12.0.0
控件配置
PropertyTypeMandatoryDescriptionVersion
requiredbooleanfalse是否必填v12.0.0
maxnumberfalse最大值v12.0.0
minnumberfalse最小值v12.0.0
maxLengthnumberfalse最大长度v12.0.0
minLengthnumberfalse最小长度v12.0.0
arrMaxLengthnumberfalse数组最大长度v12.0.0
arrMinLengthnumberfalse数组最小长度v12.0.0
maxFileSizenumberfalse最大文件大小v12.0.0
minFileSizenumberfalse最小文件大小v12.0.0
fileTypestring[]false支持的文件类型v12.0.0
patternstring | RegExpfalse正则表达匹配v12.0.0
whitespacebooleanfalse是否可以都是空格v12.0.0
initValueanyfalse初始值v12.0.0
placeholderstringfalseplaceholderv12.0.0
key: stringanyfalse拓展配置v12.0.0

INbControlErrInfo

v12.0.0
控件错误信息
PropertyTypeMandatoryDescriptionVersion
key: stringstring|Observable<string>falsekey值为字符串类型,value值为字符串类型或者可观察者对象。key表示错误类型,value为显示到UI上的错误信息。支持直接显示和订阅显示,以便在多语言场景下使用v12.0.0

INbFormConfigs

v12.0.0
表单的控件配置
PropertyTypeMandatoryDescriptionVersion
key: stringINbControlConfigfalsekey值为表单的控件的名称,value为控件的配置信息v12.0.0

Enums

NbControlErrType

v15.0.0

NbControlErrTypeEnum

v12.0.0, 从v15.0.0开始为@deprecated
常用表单错误枚举
KeyValueDescriptionVersion
REQUIREDrequired必填错误v12.0.0
FILE_MAX_SIZEfileMaxSize最大文件大小错误v12.0.0
FILE_MIN_SIZEfileMinSize最小文件大小错误v12.0.0
FILE_TYPEfileType文件类型v12.0.0
EQUALequal相等错误v12.0.0
MAX_LENGTHmaxlength最大长度错误v12.0.0
MIN_LENGTHminlength最小长度错误v12.0.0
ARR_MAX_LENGTHarrMaxLength数组最大长度错误v12.0.0
ARR_MIN_LENGTHarrMinLength数组最小长度错误v12.0.0
WHITESPACEwhitespace空格错误v12.0.0

贡献

欢迎提feature和PR,一起使该项目更好


License

MIT