0Pricing
React Native Academy · レッスン

バリデーションルールとエラーメッセージ

rules propでrequired、minLength、patternなどの組み込みバリデーションルールを適用し、各フィールドの下にerrorオブジェクトを表示します。

「バリデーションルールとエラーメッセージ」はCoddyKit上の無料React Native Academyレッスンです。 これはレッスン2/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これはReact Native Academy学習パスの一部であり、ウェブとCoddyKitアプリ全体で進捗が同期されます。 React Native Academyコースには全4レッスンが含まれています。

このレッスンの一部はまだ翻訳されておらず、英語で表示されています。

Built-In Validation Rules Overview

react-hook-form provides several built-in validation rules that cover the most common requirements without writing custom code. They are: required, minLength, maxLength, min (for numeric minimum), max (for numeric maximum), and pattern (regex match). Each rule can take a simple value or an object with value and message for a custom error message.

required Rule

The required rule ensures a field is not left empty. You can pass a boolean true (which uses a generic error message) or a string (which becomes the error message). For required fields in mobile forms, always pass a descriptive message so users immediately know what is missing without guessing.

// Simple boolean — uses generic message
rules={{ required: true }}

// String shorthand — message is the string
rules={{ required: 'Please enter your email' }}

// Full object form
rules={{ required: { value: true, message: 'Email is required' } }}

minLength and maxLength Rules

Use minLength to enforce a minimum number of characters and maxLength to cap input length. These are essential for username fields (minimum 3 characters), passwords (minimum 8 characters), and bio fields (maximum 200 characters). Both rules compare the string's length property against the value you specify.

rules={{
  required: 'Username is required',
  minLength: {
    value: 3,
    message: 'Username must be at least 3 characters',
  },
  maxLength: {
    value: 20,
    message: 'Username cannot exceed 20 characters',
  },
}}

pattern Rule for Regex Validation

The pattern rule tests the field value against a regular expression. Use it for email format, phone numbers, postal codes, or any structured text format. Pass the regex as the value property. React-hook-form tests the entire string against the pattern, so you typically do not need anchors.

// Email validation
rules={{
  pattern: {
    value: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,
    message: 'Please enter a valid email address',
  },
}}

// Phone number (digits only, 10-15 chars)
rules={{
  pattern: {
    value: /^[0-9]{10,15}$/,
    message: 'Enter a valid phone number (digits only)',
  },
}}

min and max Rules for Numbers

For numeric inputs — quantities, ages, prices — use min and max rules. They compare the numeric value of the input string, not its length. Set keyboardType='numeric' on the TextInput to help users enter numbers. Combine with pattern to ensure only digits are entered.

rules={{
  required: 'Age is required',
  min: { value: 18, message: 'You must be at least 18 years old' },
  max: { value: 120, message: 'Please enter a valid age' },
  pattern: {
    value: /^[0-9]+$/,
    message: 'Age must be a whole number',
  },
}}

Custom Validation with validate

The validate rule accepts a function (or an object of named functions) that receives the current field value and returns true if valid or an error message string if invalid. Use it for complex requirements that built-in rules cannot express, such as confirming passwords match or checking whether a username is already taken via an async API call.

// Single custom validator
rules={{
  validate: (value) =>
    value.includes('@') || 'Email must contain an @ symbol',
}}

// Multiple named validators
rules={{
  validate: {
    notEmpty: (v) => v.trim().length > 0 || 'Cannot be blank',
    noSpaces: (v) => !v.includes(' ') || 'No spaces allowed',
  },
}}

Async validate for Server-Side Checks

The validate function can be async. This is useful for checking whether a username or email is already taken. The function receives the input value, makes an API call, and returns an error string if the value is already in use or true (or undefined) if it is available. The input is marked invalid until the async check resolves.

rules={{
  validate: async (email) => {
    try {
      const { available } = await api.checkEmailAvailability(email);
      return available || 'This email is already registered';
    } catch {
      return true; // Allow if check fails — server will catch it later
    }
  },
}}

Accessing Errors from formState

formState.errors is a nested object where each key is a field name and the value is an error object with a type (which rule failed) and a message (the error string). Access a field's error with errors.fieldName?.message — the optional chaining prevents runtime errors when the field has no error.

const { formState: { errors } } = useForm();

// Accessing errors:
console.log(errors.email?.type);    // 'required' | 'pattern' | 'validate'
console.log(errors.email?.message); // 'Email is required'

// Checking if any error exists:
const hasError = !!errors.email;

// Getting error from a named validate:
console.log(errors.username?.type); // 'noSpaces'

Styling Inputs Based on Error State

Provide immediate visual feedback by changing the input's border color when it has an error. Pass the error state as a conditional style using an array of styles. A red border on the invalid field plus a red error message text below creates a clear, standard pattern that users recognize from web forms.

const styles = StyleSheet.create({
  input: {
    borderWidth: 1,
    borderColor: '#ccc',
    borderRadius: 8,
    padding: 12,
  },
  inputError: {
    borderColor: '#d32f2f',
  },
  errorText: {
    color: '#d32f2f',
    fontSize: 12,
    marginTop: 4,
  },
});

<TextInput style={[styles.input, errors.email && styles.inputError]} />
{errors.email && <Text style={styles.errorText}>{errors.email.message}</Text>}

Controlling When Errors Appear

By default, errors only show after the first submit attempt. After that, react-hook-form re-validates in real time as the user fixes each field. You can change this with the mode option passed to useForm. The 'onBlur' mode shows errors as soon as a field loses focus, which gives earlier feedback without distracting red messages while the user is still typing.

const form = useForm<SignUpForm>({
  mode: 'onBlur',        // validate on field blur
  reValidateMode: 'onChange', // re-validate on every change after first error
  defaultValues: { name: '', email: '', password: '' },
});

Server-Side Errors with setError

After the form passes client-side validation and the API call fails with a server error — like 'Email already exists' — use setError to inject an error into a specific field. This re-triggers the error display for that field, giving the user precise feedback without re-running all validation rules from scratch.

const { setError, handleSubmit } = useForm<RegisterForm>();

async function onSubmit(data: RegisterForm) {
  try {
    await api.register(data);
    navigation.replace('Home');
  } catch (err: any) {
    if (err.code === 'EMAIL_EXISTS') {
      setError('email', {
        type: 'server',
        message: 'This email is already registered. Please log in.',
      });
    }
  }
}

Quick Check

Test your understanding of React Native Mobile Development concepts from this lesson.

Lesson Recap

In this lesson you learned: built-in rules (required, minLength, maxLength, pattern, min, max) cover most validation needs, validate handles complex and async custom checks, and setError injects server-side errors into specific fields after a failed API call. Next up we explore building multi-step forms with form state.

よくある質問

「バリデーションルールとエラーメッセージ」レッスンは無料ですか?

はい。「バリデーションルールとエラーメッセージ」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、React Native Academyコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 React Native Academyコースには全4レッスンが含まれています。

「バリデーションルールとエラーメッセージ」で何を学びますか?

rules propでrequired、minLength、patternなどの組み込みバリデーションルールを適用し、各フィールドの下にerrorオブジェクトを表示します。 ブラウザで直接実行するハンズオンコードでReact Native Academyを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。

React Native Academyを始めるのに経験は必要ですか?

事前経験は必要ありません。CoddyKitのReact Native Academyは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン2/4です。

「バリデーションルールとエラーメッセージ」レッスンにはどのくらい時間がかかりますか?

ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。

このReact Native Academyレッスンでコードを書いて実行できますか?

はい。すべてのReact Native Academyレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。

このコースのすべてのレッスン

  1. Controllerを使ったreact-hook-formのセットアップ
  2. バリデーションルールとエラーメッセージ
  3. フォームの状態を使ったマルチステップフォーム
  4. フォームの送信とリセット
← React Native Academyに戻る