项目作者: locphan87

项目描述 :
Reusable form validators for formik
高级语言: TypeScript
项目地址: git://github.com/locphan87/formik-validators.git
创建时间: 2018-09-18T05:54:35Z
项目社区:https://github.com/locphan87/formik-validators

开源协议:

下载


Formik Validators

Reusable field-level form validators for formik, support i18n

Table of Contents

Getting started

  • Install with npm
  1. $ npm install formik-validators
  • Install with yarn
  1. $ yarn add formik-validators

Basic usage

  1. // myModule.form.ts
  2. import validator, { required, minLength, maxLength } from 'formik-validators'
  3. const InnerForm = props => {
  4. return (
  5. <View>
  6. <TextInput
  7. {...getFieldProps(props, 'phoneNumber')}
  8. name={'phoneNumber'}
  9. placeholder={'Enter your phone number'}
  10. ></TextInput>
  11. </View>
  12. )
  13. }
  14. const MyForm = withFormik({
  15. validate: validator({
  16. phoneNumber: [
  17. required('errors.phone.required'),
  18. minLength(8)('errors.phone.minLength'),
  19. maxLength(10)('errors.phone.maxLength')
  20. ]
  21. })
  22. })(InnerForm)

Custom the translate function

By default, the translate function would return the same string that you give it

  1. translateFn = (term, params) => term

But you can create your own translate function.

  1. // validator.ts
  2. import I18n from 'i18n-js'
  3. import validator, { setTranslateFn } from 'formik-validators'
  4. setTranslateFn((term, params) => I18n.t(term, params))
  5. export default validator
  1. // ../../forms/index.ts
  2. export { default as validator } from './validator'
  3. export * from './forms.components' // i.e TextInput, Checkbox, TextArea,...
  1. // myModule.form.ts
  2. import { validator, TextInput } from '../../forms'
  3. import { required, minLength, getFieldProps } from 'formik-validators'
  4. ...
  1. // locales/en.ts
  2. export default {
  3. 'errors.phone.required': 'Phone number is required',
  4. 'errors.phone.minLength': 'Phone number must be at least {{length}} digits',
  5. 'errors.phone.minLength': 'Please enter a maximum of {{length}} digits'
  6. }

Add new validation rules

formik-validators comes with some basics validation rules, but it’s not enough for building a real world app.

Despite that, it is easy for adding your custom rules.

Example: add a new rule to check the exact length

  1. const exactLength = (length: number, errorKey: string): RuleFn => ({
  2. value, values, props
  3. }: RuleInput) => {
  4. if (isNil(value)) return
  5. if (value.length !== length) {
  6. return t(errorKey, { length })
  7. }
  8. }

Licensing

MIT