18.0.0 • Published 1 year ago

@bigbear713/nb-form v18.0.0

Weekly downloads
-
License
MIT
Repository
github
Last release
1 year ago

@bigbear713/nb-form

Angular common form lib by bigBear713.

OnlineDemo

Bug Report

Feature Request

Document


Changelog


Feature

  • Provide the common validators: arrLength, equal, fileSize, fileType, required, whitespace. You can see the definition below;
  • Support to use DI to set common error info;
  • Support the changeDetection of components as ChangeDetectionStrategy.OnPush;
  • Support to used in standalone component;
  • Support to be imported as a standalone component;

Version

The nb-form's major version will keep up with the Angular's major version
@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
^18.0.0^18.0.0

Installation

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

API

Module

NbFormModule

Form module. After importing the module, you can use the component. The service and validators also can be used if you don't import the module.

NbFormTestingModule

Form testing module, used fo unit test.

Validators

NbFormValidators.arrLength

v12.0.0
Array length validator
Params
NameTypeMandatoryDescriptionVersion
arrLength{ max?: number; min?: number }trueThe limit about array length. You can set max/min value alonev12.0.0
Return
TypeDescription
{ [NbControlErrType.ARR_MAX_LENGTH]?: true;[NbControlErrType.ARR_MIN_LENGTH]?: true; }|nullThe result. If it is null, the condition is met or the value of control is not a array value. If the result is { [NbControlErrType.ARR_MAX_LENGTH]: true }, the control array value's length is greater than max limit value. If the result is { [NbControlErrType.ARR_MIN_LENGTH]: true }, the control array value's length is less than the min limit value.
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(minC  ontrol.errors); // { [NbControlErrType.ARR_MIN_LENGTH]: true }

NbFormValidators.equal

v12.0.0
Values are equal validator. When the values of the controls are not equal, only the target control will have the no equal error info. If you want to make the target and compared control all have the error info, can refer to the demo
Params
NameTypeMandatoryDescriptionVersion
comparedAbstractControltrueThe control which will be compared with the current controlv12.0.0
immediatelybooleanfalseVerify immediately. If set it as false, it will verify the value until the compared control is dirty. The default is truev12.1.0
Return
TypeDescription
{ [NbControlErrType.NOT_EQUAL]: true; }|nullThe result. If the two control's values are equal, the result is null. If the valus are not equal, the result is { [NbControlErrType.NOT_EQUAL]: true }. When the values are not equal, the compared control will has the no equal error info.
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
File size validator
Params
NameTypeMandatoryDescriptionVersion
fileSize{ max?: number; min?: number }trueThe limit of file size. You can set the max/min limit alone. The limit value's unit is B.v12.0.0
Return
TypeDescription
{ [NbControlErrType.FILE_MAX_SIZE]?: true;[NbControlErrType.FILE_MIN_SIZE]?: true; }|nullThe result. If is is null, the condition is met or the control's value is not a File type value. If the result is { [NbControlErrType.FILE_MAX_SIZE]: true }, the file size is greater than the max limit value. If the result is { [NbControlErrType.FILE_MIN_SIZE]: true }, the file size is less than the min limit value.
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
File type validator
Params
NameTypeMandatoryDescriptionVersion
typesstring[]trueThe file types you want to support. The types value should be MIME Type value.v12.0.0
Return
TypeDescription
{ [NbControlErrType.FILE_TYPE]: true; }|nullThe result. If it is null, the condition is met or the value of control is not a Filevalue. If the result is { [NbControlErrType.FILE_TYPE]: true }, the control's file type is among the types to be supported
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
Required validator
Params
NameTypeMandatoryDescriptionVersion
requiredbooleanfalseIs the control required. The default is true. If the param is true, it will call the Validators.required, otherwise it will not do the checkv12.0.0
Return
TypeDescription
{ [NbControlErrType.REQUIRED]: true; }|nullThe result. If it is null, the condition is met. If the result is { [NbControlErrType.REQUIRED]: true }, the control's value shoule be required.
Usage
const control = new FormControl('',[NbFormValidators.required(true)])
console.log(control.errors); // { [NbControlErrType.REQUIRED]: true; }

NbFormValidators.whitespace

v12.0.0
Can all be whitespace validator
Params
NameTypeMandatoryDescriptionVersion
canWhitespacebooleanfalseCan the control's value all be whitespace? The default is true. If the param is true, user can only enter whitespaces.v12.0.0
Return
TypeDescription
{ [NbControlErrType.WHITESPACE]: true; }|nullThe result. If it is null, the condition is met. If the result is { [NbControlErrType.WHITESPACE]: true }, the condition is not met.
Usage
const control =new FormControl('    ',[NbFormValidators.whitespace(false)])
console.log(control.errors); // { [NbControlErrType.WHITESPACE]: true; }

Services

NbFormService

v12.0.0
A service which provide some common function about form
Methods
NameReturnDescriptionScenesVersion
getValidatorsFromControlConfig(config: INbControlConfig)ValidatorFn[]Get the validator list based on the config param. The config you can set inlcude required,max,min,maxLength,minLength,arrMaxLength,arrMinLength,maxFileSize,minFileSize,fileType,pattern,whitespace. And max,min,maxLength,minLength,pattern will return the validators from Validators, others is from NbFormValidatorsWhen you need to quickly set the validator list based on configuration informationv12.0.0
markAllAsDirty(control: NbAbstractControl, opts?: { onlySelf?: boolean; emitEvent?: boolean; })voidMark the control and its sub-controls as dirty. The control is the target which you want to mark, opts param will be set to the control and its sub-controlsIf you want to mark a control and its sub-controls as dirtyv12.0.0
showAllErrInfo(control: NbAbstractControl, opts?: { onlySelf?: boolean; emitEvent?: boolean; })voidShow the control and its sub-controls all error information. It will call the control.markAllAsTouched,markAllAsDirty,updateAllValueAndValidity functions to make the error info be displayed on UI. The control is the target you want to do. The opts param will be set to the control and its sub-controls when calling the markAllAsDirty,updateAllValueAndValidity functionsWhen you want to show the error info of control and its sub-controls to user, like submitting the formv12.0.0
updateAllValueAndValidity(control: NbAbstractControl, opts?: { onlySelf?: boolean; emitEvent?: boolean; })voidUpdate the control and its sub-controls vaules and validities. The control param is the target you want to do, opts param will be set to the control and its sub-controlsWhen you want to update the control and its sub-controls vaules and validitiesv12.0.0
updateEqualControlsValidities(controls: { target: AbstractControl; compared: AbstractControl }, destroy$?: Subject)SubscriptionUpdate the validities of the controls which want to be equal. The event will be done until one of the tow controls' status has been changed. This is a subscribe event and the return value of the function is the subscribe event index. So you can unsubribe it via the return value. Also you can input a destroy$ param and next a value via the destroy$ param to unsubscribe the event.You can use it with NbFormValidators.equal validator, so the two controls' equal status can be updated in time, e.g. when change password, verify the new password and repeat new password are equalv12.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};
// unsubscribe it via return value
const subscription = this.updateEqualControlsValidities(controls);
subscription.unsubscribe();
// unsubscribe it via destroy$
const destroy$ = new Subject<void>();
this.updateEqualControlsValidities(controls,destroy$);
destroy$.next();
destroy$.complete();

Components

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

v12.0.0
Be a standalone component from v15.1.0
The component is used to show error info of the control. The error info support string and Observable<string> type, so you can use it in i18n. You can set common error info in providers, it will combined with error info which is inputed from the component.
Input
NameTypeMandatoryDefaultDescriptionVersion
controlAbstractControltrue-The control which the error info belong. The prop is required start from v16.0.0.v12.0.0
errInfoINbControlErrInfofalse{}Error information which only belong the control. It will combined with the common error infos which are set in providers.v12.0.0
Usage
<!-- control = new FormControl() -->
<!-- errInfo = {required:'This field is required!'} -->
<nb-control-err [control]="control" [errInfo]="errInfo" />

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

// imported in standalone component
@Component({
  standalone:true,
  imports:[NbControlErrComponent],
  // ...
})
export class XXXComponent{}

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

v12.0.0
Be a standalone component from v15.1.0
The file item component, is used in form in common. It has common layout and can show error info
[field-label]
The file item's label
Input
NameTypeMandatoryDefaultDescriptionVersion
controlAbstractControl | undefinedfalse-The control which error info belong.v12.0.0
errInfoINbControlErrInfofalse{}The error information. If it is undefined, the final error info is only the common error info from providersv12.0.0
requiredbooleanfalsefalseIs the field required? If is is true, there will display "*". The default is falsev12.0.0
Usage
<!-- set the field's label and field content. If there does not have control params, the error info will not be displayed -->
<nb-field-item>
  <ng-container field-label>field 1</ng-container>
  <input>
</nb-field-item>

<!-- Set the filed is required, and will display the error info -->
<nb-field-item [required]="true" [control]="control" [errInfo]="errInfo">
  <ng-container field-label>field 2</ng-container>
  <input>
</nb-field-item>
// New in the v15.1.0
// imported in NgModule
@NgModule({
  imports:[NbFieldItemComponent],
  // ...
})
export class XXXModule{}

// imported in 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, @deprecated from v15.0.0
Used to set common error info, so you don't need to set the common error info every where. If you set the common error info, it will auto be combined with the error info of <nb-control-err></nb-control-err> to be final error info.
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
Abstract control, include AbstractControl, null, undefined

INbControlConfig

v12.0.0
The config of control
PropertyTypeMandatoryDescriptionVersion
requiredbooleanfalseIs required limitv12.0.0
maxnumberfalseMax limitv12.0.0
minnumberfalseMin limitv12.0.0
maxLengthnumberfalseMax length limitv12.0.0
minLengthnumberfalseMin length limitv12.0.0
arrMaxLengthnumberfalseMax length limit of arrayv12.0.0
arrMinLengthnumberfalseMin length limit of arrayv12.0.0
maxFileSizenumberfalseMax size limit of filev12.0.0
minFileSizenumberfalseMin size limit of filev12.0.0
fileTypestring[]falseThe types limit of filev12.0.0
patternstring | RegExpfalseThe pattern limitv12.0.0
whitespacebooleanfalseCan all be whitespacev12.0.0
initValueanyfalseInitial valuev12.0.0
placeholderstringfalseplaceholderv12.0.0
key: stringanyfalsemore configsv12.0.0

INbControlErrInfo

v12.0.0
Error informations. The key is the type of error, the value is error information
PropertyTypeMandatoryDescriptionVersion
key: stringstring|Observable<string>falseThe key is string type, and the value is string or Observable type, so you can use it in i18nv12.0.0

INbFormConfigs

v12.0.0
The configs of form control
PropertyTypeMandatoryDescriptionVersion
key: stringINbControlConfigfalseThe key is the control's name, the value is control's configsv12.0.0

Enums

NbControlErrType

v15.0.0

NbControlErrTypeEnum

v12.0.0, @deprecated from v15.0.0
Common error enum
KeyValueDescriptionVersion
REQUIREDrequiredRequired errorv12.0.0
FILE_MAX_SIZEfileMaxSizeFile max size errorv12.0.0
FILE_MIN_SIZEfileMinSizeFile min size errorv12.0.0
FILE_TYPEfileTypeFile type errorv12.0.0
EQUALequalEqual errorv12.0.0
MAX_LENGTHmaxlengthMax length errorv12.0.0
MIN_LENGTHminlengthMin length errorv12.0.0
ARR_MAX_LENGTHarrMaxLengthMax length of array errorv12.0.0
ARR_MIN_LENGTHarrMinLengthMin length of array errorv12.0.0
WHITESPACEwhitespacewhitespace errorv12.0.0

Contribution

Feature and PR are welcome to make this project better together


License

MIT