@naologic/forms

__

Stats

stars 🌟issues ⚠️updated 🛠created 🐣size 🏋️‍♀️
@naologic/forms
Minified + gzip package size for @naologic/forms in KB

Readme

@naologic/forms from :fireworks: Alexandria Library

__

:page_with_curl: Install

npm install --save @naologic/forms

Use

NaoValidators

Import the validators to your component

import { NaoValidators } from '@naologic/forms'
Available Methods
  • min()
  • max()
  • inArray()
  • inObjectKey()
  • inObject()
  • inEnum()
  • inEnumKey()
  • isSSN()
  • isUSZip()
  • isUSPhone()
  • solveOne()
  • solveSome()
  • solveNone()
  • solveAll()

FormControl Validators

min()

min(value) Validator that requires controls to have a value greater than a number.

Arguments
  • value(number) minimum value required.
Returns
  • ValidationErrors | null

Example

    public userForm: FormGroup;
    
    this.userForm = new FormGroup({
        fruit: new FormControl(11, NaoValidators.min(7));
        // => Input validation will pass, 11 is greater than 7
    });

max()

max(value) Validator that requires controls to have a value less than a number.

Arguments
  • value(number) maximum value allowed.
Returns
  • ValidationErrors | null

Example

    public userForm: FormGroup;
    
    this.userForm = new FormGroup({
        fruit: new FormControl(11, NaoValidators.max(12));
        // => Input validation will pass, 11 is less than 12
    });

inArray()

inArray(array) Validator that checks if control value exists in provided array

Arguments
  • array(Array) The array to check.
Returns
  • ValidationErrors | null

Example

    public arr = ['apple', 'orange', 'lemon', 'melon'];
    public userForm: FormGroup;
    
    this.userForm = new FormGroup({
        fruit: new FormControl('lemon', NaoValidators.inArray(this.arr));
        // => Input validation will not pass, 'lemon' is an element of 'arr' Array
    });

inObjectKey()

inObjectKey(object) Validator that checks if control value exists in provided object key

Arguments
  • object(Object) The object to check.
Returns
  • ValidationErrors | null

Example

    public obj = {
        small: 'S',  
        medium: 'M',
        large: 'L'
    };
    public userForm: FormGroup;
    
    this.userForm = new FormGroup({
        size: new FormControl('small', NaoValidators.inObjectKey(this.obj));
        // => Input validation will not pass, 'small' is a key of 'obj' Object
    });

inObject()

inObject(object, path) Validator that checks if control value exists in provided object

Arguments
  • object(Object) The object to check.
  • path(string) Path to check (must not be empty).
Returns
  • ValidationErrors | null

Example

    public user = {
    email: 'jack@dev.com',
    personalInfo: {
            name: 'Jack',
            address: {
                line1: 'westwish st',
                line2: 'washmasher',
                city: 'wallas',
                state: 'WX'
            }
        }
    }
    public userForm: FormGroup;
    
    this.userForm = new FormGroup({
        size: new FormControl('wallas', NaoValidators.inObject(this.user, 'user.personalInfo.address.city'));
        // => Input validation will not pass, 'wallas' is a value of 'user' Object.
    });
    console.log(user.personalInfo.address.city);
    // => "wallas"

inEnumKey()

inEnumKey(EnumObj) Validator that checks if control value exists in provided enum object

Arguments
  • enumObj(Object) The enum object to check.
Returns
  • ValidationErrors | null

Example

    enum DaysOfWeek { SUN, MON, TUE}
    public userForm: FormGroup;
    
    this.userForm = new FormGroup({
        size: new FormControl('SUN', NaoValidators.inEnumKey(DaysOfWeek));
        // => Input validation will not pass, 'SUN' is a key of 'DaysOfWeek' enum Object.
    });
    console.log(DaysOfWeek);
    // => {0: "SUN", 1: "MON", 2: "TUE", SUN: 0, MON: 1, TUE: 2}

inEnum()

inEnum(EnumObj) Validator that checks if the control value matches any of the enum values

Arguments
  • enumObj(Object) The enum object to check.
Returns
  • ValidationErrors | null

Example

    enum DaysOfWeek { SUN = 'Sunday', MON = 'Monday', TUE = 'Tuesday'}
    public userForm: FormGroup;
    
    this.userForm = new FormGroup({
        size: new FormControl('Monday', NaoValidators.inEnum(DaysOfWeek));
        // => Input validation will not pass, 'Monday' is a value of 'DaysOfWeek' enum Object.
    });
    console.log(DaysOfWeek);
    // => {SUN: "Sunday", MON: "Monday", TUE: "Tuesday"}

isSSN()

isSSN() Validator that checks if control value is a valid US SSN

Returns
  • ValidationErrors | null

Example

    public userForm: FormGroup;
    
    this.userForm = new FormGroup({
        ssn: new FormControl('123 45 6789', NaoValidators.isSSN());
        //--> Input validation will pass
        // --> Accepted format 123 445 6789, 123-445-6789, 1234456789
    });

isUSZip()

isUSZip() Validator that checks if control value is a valid format of US Zip Code

Returns
  • ValidationErrors | null

Example

    public userForm: FormGroup;
    
    this.userForm = new FormGroup({
         zip: new FormControl('65567', NaoValidators.isUSZip()),
        // => Input validation will pass
    });

isUSPhone()

isUSPhone() Validator that checks if control value is a valid US Phone format

Returns
  • ValidationErrors | null

Example

    public userForm: FormGroup;
    
    this.userForm = new FormGroup({
         phone: new FormControl('123 445 6789', NaoValidators.isUSPhone()),
        // --> Input validation will pass
        // --> Accepted format  123 445 6789, 123-445-6789, 1234456789
    });

FormGroup Validators


solveOne()

solveOne(conditions) Validator that checks if ONLY ONE condition is true

Arguments
  • conditions(Array) Multiple Arrays of strings following this format [value_1, operator, value_2] Available opertators <, >, <=, >=, ==, != ex: ['name', '==', 'animals[0].type'], ['weight', '!=', 'animals[0].weight'] Check the example below
Returns
  • ValidationErrors | null

Example

    public groupForm: FormGroup;

    constructor( private fb: FormBuilder) {
       this.groupForm = this.fb.group({
         name: 'Tiger',
         weight: 85,
         animals: this.fb.array([
           this.fb.group({
             type: 'Tiger',
             weight: 85
           })
         ])
       }, { validator: NaoValidators.solveOne(['name', '==', 'animals[0].type'], ['weight', '==', 'animals[0].weight']) });
        // --> Form validation will fail (both conditions are true)
        // -->  This will pass validation ex: NaoValidators.solveOne(['weight', '==', 'animals[0].weight'])
    }

solveSome()

solveSome(conditions) Validator that checks if at least one condition is truee

Arguments
  • conditions(Array) Multiple Arrays of strings following this format [value_1, operator, value_2] Available opertators <, >, <=, >=, ==, != ex: ['name', '!=', 'animals[0].type'], ['weight', '>', 'animals[0].weight'] Check the example below
Returns
  • ValidationErrors | null

Example

    public groupForm: FormGroup;

    constructor( private fb: FormBuilder) {
       this.groupForm = this.fb.group({
         name: 'Tiger',
         weight: 85,
         animals: this.fb.array([
           this.fb.group({
             type: 'Tiger',
             weight: 75
           })
         ])
       }, { validator: NaoValidators.solveSome(['name', '==', 'animals[0].type'], ['weight', '==', 'animals[0].weight']) });
        // --> Form validation will pass, one of the conditions is true ['name', '==', 'animals[0].type']
    }

solveNone()

solveNone(conditions) Validator that checks if NONE of the condition are true

Arguments
  • conditions(Array) Multiple Arrays of strings following this format [value_1, operator, value_2] Available opertators <, >, <=, >=, ==, != ex: ['name', '==', 'animals[0].type'], ['weight', '<', 'animals[0].weight'] Check the example below
Returns
  • ValidationErrors | null

Example

    public groupForm: FormGroup;

    constructor( private fb: FormBuilder) {
       this.groupForm = this.fb.group({
         name: 'Tiger',
         weight: 85,
         animals: this.fb.array([
           this.fb.group({
             type: 'Tiger',
             weight: 75
           })
         ])
       }, { validator: NaoValidators.solveNone(['name', '==', 'animals[0].type'], ['weight', '==', 'animals[0].weight']) });
        // --> Form validation will fail, one of the conditions is true ['name', '==', 'animals[0].type']
    }

solveAll()

solveAll(conditions) Validator that checks if ALL condition are true

Arguments
  • conditions(Array)
    Multiple Arrays of strings following this format [value_1, operator, value_2] Available opertators <, >, <=, >=, ==, != ex: ['name', '!=', 'animals[0].type'], ['weight', '>=', 'animals[0].weight'] Check the example below
Returns
  • ValidationErrors | null

Example

    public groupForm: FormGroup;

    constructor( private fb: FormBuilder) {
       this.groupForm = this.fb.group({
         name: 'Tiger',
         weight: 85,
         animals: this.fb.array([
           this.fb.group({
             type: 'Tiger',
             weight: 75
           })
         ])
       }, { validator: NaoValidators.solveAll(['name', '==', 'animals[0].type'], ['weight', '==', 'animals[0].weight']) });
         // --> Form validation will fail, only one condition is true ['name', '==', 'animals[0].type']
    }

NaoFormGrop


Import NaoFormGroup to your component

import { NaoFormGroup } from '@naologic/forms'
Available Methods
  • getValue()
  • getValues()
  • disable()
  • patchDeep()
  • validate()
  • addJSONSchema()
  • removeJSONSchema()
  • getAllErrors()
  • getAllErrorsFlat()

getValue()

getValue() Get form values object

Returns
  • Object

Example

    public naoFormGroup: NaoFormGroup;

    this.naoFormGroup = new NaoFormGroup({
      first: new NaoFormControl('first'),
      second: new NaoFormControl('second'),
    });
    
   const formValues = this.naoFormGroup.getValue();
   console.log(formValues);
   // --> {first: "first", second: "second"}
   console.log(formValues.first);
   // --> first

getValues()

getValue(indexes) Get specific form values

Arguments
  • indexes(string)
Returns
  • Object

Example

    public naoFormGroup: NaoFormGroup;

    this.naoFormGroup = new NaoFormGroup({
      first: new NaoFormControl('First control'),
      second: new NaoFormControl('Second control'),
      third: new NaoFormControl('Third control'),
    });
    
   const formValues = this.naoFormGroup.getValues('first', 'second');
   console.log(formValues);
   // --> {first: "First control", second: "Second control"}

disable()

disable(opts) Disables the control. This means the control is exempt from validation checks and excluded from the aggregate value of any parent. Its status is DISABLED.

Arguments
  • opts(Object) - optional argument opts Configuration options that determine how the control propagates changes and emits events after the control is disabled.
    {onlySelf?: boolean, emitEvent?: boolean}
    
    onlySelf: When true, mark only this control. When false or not supplied, marks all direct ancestors. Default is false.. emitEvent: When true or not supplied (the default), both the statusChanges and valueChanges observables emit events with the latest status and value when the control is disabled. When false, no events are emitted.
Returns
  • void

Example

    public naoFormGroup: NaoFormGroup;

    this.naoFormGroup = new NaoFormGroup({
      details: new NaoFormGroup({
        fullName: new NaoFormControl('John Doe'),
        // --> 'ssn' form control with invalid value
        ssn: new NaoFormControl('000 00 0000', NaoValidators.isSSN()),
      }),
      address: new NaoFormGroup({
        // --> 'zip' form control with invalid value
        zip: new NaoFormControl('00000', NaoValidators.isUSZip()),
        street: new NaoFormControl('7821 Princess St.'),
      }),
    });
    
    // We exclude 'details' from Form validation check
   this.naoFormGroup.controls.details.disable();
   // Console log all Form errors
   console.log(this.naoFormGroup.getAllErrors());
   // --> { address: { zip: { ok: false, isUSZip: false, actualValue: "00000"} } }

patchDeep()

patchDeep(data) Patches the value of the FormGroup. It accepts an object with control names as keys, and does its best to match the values to the correct controls in the group.

Arguments
  • data(any)
Returns
  • void

Example

    public naoFormGroup: NaoFormGroup;

    this.naoFormGroup = new NaoFormGroup({
      first: new NaoFormControl(),
      last: new NaoFormControl(),
    });
    
    console.log(this.naoFormGroup.value);
   // --> {first: null, last: null}
   
   this.naoFormGroup.patchValue({first: 'Nancy'});
   console.log(this.naoFormGroup.value); 
   // --> {first: 'Nancy', last: null}

getAllErrors()

getAllErrors() Get all errors from this form

Returns
  • null | object

Example

    public naoFormGroup: NaoFormGroup;

    this.naoFormGroup = new NaoFormGroup({
      firstName: new NaoFormControl('John'),
      lastName: new NaoFormControl('Doe'),
      // -->  'ssn' Form control with invalid value
      ssn: new NaoFormControl('000 00 0000', NaoValidators.isSSN()),
    });
    
   const getFormErrors = this.naoFormGroup.getAllErrors();
   console.log(getFormErrors);
   // --> {first: {ok: false, isSSN: false, actualValue: "000 00 0000"}}

getAllErrorsFlat()

getAllErrorsFlat(path) List the errors in a flat map

Arguments
  • path(string)
Returns
  • Object

Example

    public naoFormGroup: NaoFormGroup;

    this.naoFormGroup = new NaoFormGroup({
      details: new NaoFormGroup({
        fullName: new NaoFormControl('John Doe'),
        // --> 'ssn' form control with invalid value
        ssn: new NaoFormControl('000 00 0000', NaoValidators.isSSN()),
      })
    });
    
   const getFormErrors = this.naoFormGroup.getAllErrors('details');
   console.log(getFormErrors);
   // --> {details.ssn: {ok: false, isSSN: false, actualValue: "000 00 0000"}}

NaoFormArray

Import NaoFormArray to your component

import { NaoFormArray } from '@naologic/forms'
Available Methods
  • getLast()
  • getAllErrors()
  • getAllErrorsFlat()

getLast()

getLast() Get last item from FormArray

Returns
  • AbstractControl

Example

    public naoFormArray: NaoFormArray;

    this.naoFormArray =  new TestFormArray([
      new NaoFormControl('Control 1'),
      new NaoFormControl('Control 2'),
      new NaoFormControl('Control 3'),
    ]);
    const lastItem = this.naoFormArray.getLast();
    console.log(lastItem.value);
    // --> Control 3

getAllErrorsFlat()

getAllErrorsFlat(path) List the errors in a flat map

Arguments
  • path(string) - Optional argument
Returns
  • Object

Example

    public naoFormArray: NaoFormArray;

    this.naoFormArray =  new NaoFormArray([
      new NaoFormGroup({
        name: new NaoFormControl('John Doe'),
        // invalid ssn
        ssn: new NaoFormControl('00 000 0000', NaoValidators.isSSN()),
      }),
      new NaoFormGroup({
        name: new NaoFormControl('Jane Doe'),
        ssn: new NaoFormControl('34 544 7646', NaoValidators.isSSN()),
      })
    ]);
    
   console.log(this.naoFormArray.getAllErrorsFlat());
   // --> { [0].ssn: {ok: false, isSSN: false, actualValue: "000 00 0000"} }

getAllErrors()

getAllErrors() Get all errors from this form

Returns
  • Object[]

Example

    public naoFormArray: NaoFormArray;

    this.naoFormArray =  new NaoFormArray([
      new NaoFormGroup({
        name: new NaoFormControl('John Doe'),
        // invalid ssn
        ssn: new NaoFormControl('00 000 0000', NaoValidators.isSSN()),
      }),
      new NaoFormGroup({
        name: new NaoFormControl('Jane Doe'),
        ssn: new NaoFormControl('34 544 7646', NaoValidators.isSSN()),
      })
    ]);
    
   console.log(this.naoFormArray.getAllErrors());
   // --> [{ 0: { ssn: {ok: false, isSSN: false, actualValue: "000 00 0000"}} }]


gt()

gt(value) Check if the current formControl value is greater then a number

Arguments
  • value(number)
Returns
  • true | false

Example

    public fg: NaoFormGroup;
    
    this.fg = new NaoFormGroup({
        number: new NaoFormControl(20),
    });

    console.log(this.fg.getAsNaoFormControl('number').gt(10));
    // --> true


lt()

lt(value) Check if the current formControl value is less then a number

Arguments
  • value(number)
Returns
  • true | false

Example

    public fg: NaoFormGroup;
    
    this.fg = new NaoFormGroup({
        number: new NaoFormControl(20),
    });

    console.log(this.fg.getAsNaoFormControl('number').lt(10));
    // --> false


eq()

eq(value) Check if the current formControl value is equal to a value

Arguments
  • value(string | number | boolean)
Returns
  • true | false

Example

    public fg: NaoFormGroup;
    
    this.fg = new NaoFormGroup({
        number: new NaoFormControl(20),
        string: new NaoFormControl("nao")
    });

    console.log(this.fg.getAsNaoFormControl('number').eq(20));
    // --> true
    console.log(this.fg.getAsNaoFormControl('string').eq('nao'));
    // --> true


gte()

gte(value) Check if the current formControl value is greater or equal then a number

Arguments
  • value(number)
Returns
  • true | false

Example

    public fg: NaoFormGroup;
    
    this.fg = new NaoFormGroup({
        number: new NaoFormControl(20),
    });

    console.log(this.fg.getAsNaoFormControl('number').gte(20));
    // --> true


lte()

lte(value) Check if the current formControl value is less or equal then a number

Arguments
  • value(number)
Returns
  • true | false

Example

    public fg: NaoFormGroup;
    
    this.fg = new NaoFormGroup({
        number: new NaoFormControl(20),
    });

    console.log(this.fg.getAsNaoFormControl('number').lte(10));
    // --> false


not()

not(value) Check if the current formControl value is not equal with a value

Arguments
  • value(string | number | boolean)
Returns
  • true | false

Example

    public fg: NaoFormGroup;
    
    this.fg = new NaoFormGroup({
        number: new NaoFormControl(20),
        string: new NaoFormControl("nao")
    });

    console.log(this.fg.getAsNaoFormControl('number').not(20));
    // --> false
    console.log(this.fg.getAsNaoFormControl('string').not('nao'));
    // --> false


removeEmpty()

removeEmpty() Removes all the empty values ( '' | null | undefined ) from a NaoFormGroup or NaoFormArray including the nested controls

Example

    public fg: NaoFormGroup;
    
    this.fg = new NaoFormGroup({
        number: new NaoFormControl(20),
        string: new NaoFormControl("nao"),
        info: new NaoFormGroup({
            firstName: new NaoFormControl(),
            lastName: new NaoFormControl('')
        }),  
        phone: new NaoFormControl(null)
    });
    
    this.fg.removeEmpty();

    console.log(this.fg.value);
    // --> { number: 20, string: "nao" }
    


naoMask with currency

naoMask with currency nao masks that returns the formatted value on (formattedValueChange)

Example

    // ---> Input value: 124124.23
    <input naoMask="0*.00" formControlName="price"
        [currency]="{code: 'EUR', digitsInfo: '2.1-2', display: 'symbol', locale: 'en-US'}"
        [options]="{ valueFormatted: true }"
        (formattedValueChange)="fg.get('priceFormatted').patchValue($event)"/>

    <span>Formated value: {{ fg.get('priceFormatted').value }}</span>
    // ---> Formated value: €124,124.23
    

License

GitHub

Made with :heart: in San Francisco :us: by naologic

If you find any bugs or have a feature request, please open an issue on github!

The npm package download data comes from npm's download counts api and package details come from npms.io.