文章

表單處理與驗證

表單處理與驗證

在 React 懱用中,表單處理與驗證是常見的需求。妥善管理表單狀態和數據驗證不僅能提升用戶體驗,還能確保數據的正確性。以下是一些常見的表單處理和驗證的方法。


1. 基本表單處理

1.1 使用受控組件

在受控組件中,表單元素的值由 React 組件的狀態控制,這樣可以方便地管理表單數據。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import React, { useState } from 'react';

function MyForm() {
  const [inputValue, setInputValue] = useState('');

  const handleChange = (event) => {
    setInputValue(event.target.value);
  };

  const handleSubmit = (event) => {
    event.preventDefault();
    console.log('提交的數據:', inputValue);
  };

  return (
    <form onSubmit={handleSubmit}>
      <label>
        輸入:
        <input type="text" value={inputValue} onChange={handleChange} />
      </label>
      <button type="submit">提交</button>
    </form>
  );
}

export default MyForm;

1.2 使用非受控組件

在非受控組件中,表單元素的值不由 React 狀態控制,可以使用 ref 獲取其值。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import React, { useRef } from 'react';

function MyForm() {
  const inputRef = useRef(null);

  const handleSubmit = (event) => {
    event.preventDefault();
    console.log('提交的數據:', inputRef.current.value);
  };

  return (
    <form onSubmit={handleSubmit}>
      <label>
        輸入:
        <input type="text" ref={inputRef} />
      </label>
      <button type="submit">提交</button>
    </form>
  );
}

export default MyForm;

2. 表單驗證

表單驗證可以在用戶提交表單之前檢查數據的有效性。以下是常見的驗證方法。

2.1 基本驗證

可以在表單提交時進行基本的數據驗證。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
function MyForm() {
  const [inputValue, setInputValue] = useState('');
  const [error, setError] = useState('');

  const handleChange = (event) => {
    setInputValue(event.target.value);
    setError(''); // 清除錯誤
  };

  const handleSubmit = (event) => {
    event.preventDefault();
    if (inputValue.trim() === '') {
      setError('輸入不能為空');
    } else {
      console.log('提交的數據:', inputValue);
    }
  };

  return (
    <form onSubmit={handleSubmit}>
      <label>
        輸入:
        <input type="text" value={inputValue} onChange={handleChange} />
      </label>
      {error && <p style=>{error}</p>}
      <button type="submit">提交</button>
    </form>
  );
}

2.2 使用第三方驗證庫

使用像 YupFormik 這樣的庫,可以簡化表單驗證的實現。

安裝

1
npm install formik yup

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import React from 'react';
import { Formik, Field, Form, ErrorMessage } from 'formik';
import * as Yup from 'yup';

const validationSchema = Yup.object().shape({
  input: Yup.string().required('輸入不能為空'),
});

function MyForm() {
  return (
    <Formik
      initialValues=
      validationSchema={validationSchema}
      onSubmit={(values) => {
        console.log('提交的數據:', values.input);
      }}
    >
      {() => (
        <Form>
          <label>
            輸入:
            <Field type="text" name="input" />
          </label>
          <ErrorMessage name="input" component="div" style= />
          <button type="submit">提交</button>
        </Form>
      )}
    </Formik>
  );
}

export default MyForm;

3. 自定義驗證邏輯

如果需要更複雜的驗證邏輯,可以自定義驗證函數。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
const validateInput = (value) => {
  let error;
  if (value.trim() === '') {
    error = '輸入不能為空';
  } else if (value.length < 3) {
    error = '輸入必須至少三個字符';
  }
  return error;
};

function MyForm() {
  const [inputValue, setInputValue] = useState('');
  const [error, setError] = useState('');

  const handleChange = (event) => {
    setInputValue(event.target.value);
    setError(validateInput(event.target.value)); // 使用自定義驗證
  };

  const handleSubmit = (event) => {
    event.preventDefault();
    if (!error) {
      console.log('提交的數據:', inputValue);
    }
  };

  return (
    <form onSubmit={handleSubmit}>
      <label>
        輸入:
        <input type="text" value={inputValue} onChange={handleChange} />
      </label>
      {error && <p style=>{error}</p>}
      <button type="submit">提交</button>
    </form>
  );
}

4. 總結

  • 受控組件與非受控組件:根據需求選擇使用受控或非受控組件來處理表單數據。
  • 表單驗證:可以在提交時進行基本驗證,或使用第三方庫如 YupFormik 簡化驗證流程。
  • 自定義驗證邏輯:根據應用的需求,實現自定義驗證函數來滿足特定的驗證需求。

通過這些方法,你可以有效地處理和驗證 React 應用中的表單數據,提升用戶體驗和數據準確性。

本文章以 CC BY 4.0 授權