0.0.1 • Published 4 years ago

react-hook-validation-format v0.0.1

Weekly downloads
-
License
MIT
Repository
-
Last release
4 years ago
Default Action Result

Represent the value that is returned in actions like (validation ....)

  export interface IFieldsRefs {
      field : string,
      ref : RefObject<any>
    } 


  export interface IPromiseValidationData<T> {
    error : boolean,  /** true,false - form currently valid or not( has validation error or not)*/
    data : T,  /** represent validated object values */
    validations ?: IValidationModel<T> /** validation state for object */
    refs ? : IFieldsRefs[]   /** ref of fields for control fields like focus...*/
  }

example:

 const submitHandler = async () => {
   const {error,data,validations,refs} = await validation.validate()
 }

Example: Client- Submit

Reset Validation

Reset validation, clear all errors and set all fields to not dirty.
declaration

   resetValidations : (clearData ?: boolean) => void

@param clearData
true : all value in form will be reset to defaultValue or undefined -> if there is no defaultValue for the field

Remove Data Array

Use function to remove from list that has to be validated

 const validation = useValidation(...)
...
  const someHandler =  () => { 
      const { removeArrayData } = useValidation
      removeArrayData(fieldParentName as string, index as number)
  }  

Example: Client- Address

Add Data Array

Add object in one array of model. Use this if validation has more then one of same list object to validate
@field - string path of array variable like ( address, person.address...)
@data - empty object of object with data that will be default one.

   addArrayData : (field : string, data : any) => Promise<IPromiseValidationData<T>>

   const data = await validation.addArrayData('person.address', {
      zip: "10000"
     })
 

Example: Client- Address

Set Field Value

Set value to object filed

 /**
    * @param field  path of the field in object ( firstName, person.address.zip)
    * @param value  value for the field
    * @param validate  flag that indicates should validate or not after settings ( default: true)
    */ 
    setFieldValue : (field : string, value : string, validate : boolean) => void
  

Function should be used only if you want to change value of the field out of standard user input. Function is used by HOC withValidation to set value that user enter.

FieldDescription
getFieldValuefunction that returns current value for the field from state (or undefined) getField('email')
setFieldValueSet Field Value
setFieldErrorset the error for field - this error will be valid error for that field ( error is set and validation will not pass until field value is changed) setFieldError('person.firstName','User already exists')
setErrorGlobalset the error for complete model but not for particular field. Used when you get error from backend that can't be dedicated to any field, param can be string to be shown as error or just true like error exists
errorGlobalValue of error global that is set external, can be boolean,undefined,string , undefined or false - error not exists
staterepresent object of form
errorModelboolean value that shows is there one error on model
resetValidationsReset Validation
validateValidate
removeArrayData Remove Array Data
addArrayData Add Array Data
Set fields

Every input field can become a valid validation input field. Using HOC withValidation to encapsulate your component, that component becomes a component that can proceed validation.

({error,helperText,label,inputRef,value,...rest}) => {
 return (
    <div className= "form-group">
      <label className={error ? 'custom-label text-danger' : 'custom-label'}>{label}</label>
      <input
             className={`form-control ${error ? 'is-invalid' : ''}`}
             type="text"
             value={value}
             ref = {inputRef}
             {
                 ...rest
             }
      />
      { error ?  <small className="invalid-feedback custom-helper">{error}</small>  :
        (helperText ? <small className="custom-helper text-muted">{helperText}</small> : <small>&nbsp;</small>)
      }
    </div>

helper, label is user defined while inputRef ( React- ref object), value and error is provided by HOC ( withValidation) One have to implement to error ( string or true if validation error exists) and value represents current value for input

validation : {
    useValidation : IUseValidation<T> /** instance of validation hook */
    model : string    /** name of field in model (firstName, address.zip)
    defaultValue ?: string /** value that will be used for reset the form with data reseting */
    rule ? : IValidationFieldRules  /** object with validation rules */
    format ?: IFormatRuleProps /** format for field */
  }
import {
  minLength,
  required,
  useValidation
}      from 'easy-format-validation'
     ...


        const validation = useValidation()
          ...

        <MaterialTextFieldValidation
            label={'Last name'}
            helperText={'enter last name'}
            validation= {{
              useValidation: validation,
              model: 'lastName',
              rule: {
                required,> ###### <a name="set-fields">Set fields</a>
                minLength: minLength({
                  min: 2
                })
              }
            }}
        />
Performance ( rendering )

Validation makes optimization for rendering components that servers.
Optimization is based only on values ​​that are controller by HOC validation ( validation, label, helperText )
If you have additional attributes then those attributes have been passed as memoized.

First example shows right way of passing additional params ( inputProps ) Passing params in this way will not influence in control of rendering by HOC.

                            const inputPropsPayment = React.useMemo(() => {
                                return {
                                    style: {
                                        textAlign: 'right'
                                    }
                                }
                            }, [])

                              .....

                                <MaterialTextFieldValidation
                                    helperText={'payment'}
                                    label={'PAYMENT'}
                                    validation={{
                                        useValidation: validation,
                                        model: 'cardInfo.payment',
                                        defaultValue: '1000',
                                        rule: {
                                            required
                                        }
                                    }}
                                    inputProps={inputPropsPayment}
                                />

In this way input properties is every time new object, for that reason rendering of input will happen

                               <MaterialTextFieldValidation
                                   helperText={'payment'}
                                   label={'PAYMENT'}
                                   validation={{
                                       useValidation: validation,
                                       model: 'cardInfo.payment',
                                       defaultValue: '1000',
                                       rule: {
                                           required
                                       }
                                   }}
                                   inputProps={{                                    
                                               style: {
                                                           textAlign: 'right'
                                                       }
                                                   }}
                               />
0.0.1

4 years ago