DEV Community

loading...

Stories of Form - Validation

Vu Anh Duc
・2 min read

Introduction

Validation is a compulsory feature for every input form. Basically, the validation of the user's input data should be instant feedback.

Instant feedback means right after the user finishing the input, the system should provide a response about the validity of data, or at least show to the user that the validation process is running. If the data is invalid, the response should provide enough information to help the user rectify the data.

Validation logic could be based on many factors. It depends on the system's requirements, type of data,... For example:

  • Time to trigger the validation: when the user inputting, or when the user finishing the input.

  • Validation method: synchronous (input's format, comparison,...), or asynchronous (duplication, existent,...)

  • Validation data: by Field-level, or by Form-level.

  • Time to feedback: when the user opens the form, or after the user touches a field.

How does Final-Form do validation?

Firstly, final-form have 2 validation levels: Field-Level and Form-Level, by using validate attribute of <Field> and <Form> tags.
Especially, we can use both synchronous and asynchronous methods as a validation method. These methods should only care about the return result. At Field-Level, the return result should be a string which is the feedback's content in the invalid case, or undefined for the valid case. At Form-Level, the return result should be an object which has keys are the field's names and values are the feedback of fields. Or we can use a special key FORM_ERROR to set the feedback for whole form.

Tương tự như các thư viện khác, final-form cung cấp thông tin meta bao gồm các cờ thể hiện trạng thái của FieldForm nhằm hỗ trợ quyết định thời điểm thực hiện kiểm tra và thời điểm phản hồi. Các trạng thái thường dùng như:

  • pristine: còn "trinh". chưa được người dùng truy cập (focus, input,...) tới.
  • dirty: người dùng đã truy cập
  • touched: người dùng đã focus vào
  • active: người dùng đang focus
  • invalid: đã thực hiện kiểm tra và không hợp lệ
  • valid: đã kiểm tra và hợp lệ
  • validating: đang kiểm tra

Demo

Field-Level synchronous validation

Some notes:

  • We can compose some simple validations. We can use a validation library like yup. Just keep in mind the format of the output.
  • We can access other fields' value and field state inside the validation
  • By default, validation is triggered on change

Field-Level asynchronous validation

Some notes:

  • In async validation function, must use resolve in case of invalid data. reject is reserved for API's errors

  • Currently, there is an issue related to validating flag which reported here #713

Kiểm tra toàn bộ form

Discussion (0)