Showing Custom Form Validation Messages in React with setCustomValidity
When you call setCustomValidity() inside React's onInvalid handler, you can replace the messages the browser shows for its built-in checks (required, type="email", pattern) with your own text. By checking validity.valueMissing or validity.typeMismatch, you can show a different message for each kind of mistake, such as "the field is empty", "the email address format is wrong", or "too few characters". This is useful on sign-up and contact forms when the browser's English "Please fill out this field." appears, or when you want to show an example of the expected input, such as "Enter the postal code like 123-4567" (written in Japanese in the examples).
The important point is to clear the message with setCustomValidity('') whenever the input changes. If you don't, the field keeps failing validation even after the user fixes it, and the form won't submit.
The test environment was Ubuntu 24.04 and Node.js 22.23.4. I used react and react-dom 19.3.1, @types/react and @types/react-dom 19.3.0, typescript 7.0.2, esbuild 0.28.2, and Playwright 1.63.0, along with Chromium 153 launched by Playwright. I type-checked the .tsx files with tsc, transpiled them with esbuild, opened them in Chromium, and then entered values with the keyboard and pressed the submit button. I did not test Firefox, Safari, mobile browsers, Chrome with its display language set to Japanese, or screen reader announcements.
Without any changes, the messages are left to the browser
First, I created an email field with only type="email" and required. I pressed the submit button with the field empty, and then with "neko" entered. I also set the page language (navigator.language) to ja-JP in Playwright, but in the Chromium used for testing (I did not change its display language), the messages stayed in English. The following record shows each input's validity flags and the message displayed (validationMessage).
--- Submit while empty
メールアドレス: value="" valid=false [valueMissing] message="Please fill out this field."
--- "neko" と入力して送信
メールアドレス: value="neko" valid=false [typeMismatch] message="Please include an '@' in the email address. 'neko' is missing an '@'."
MDN's guide to client-side form validation also notes that the messages the browser shows depend on the browser's locale, so they may appear in a different language from the page. The wording itself is decided by the browser, so you cannot add guidance such as "like 123-4567".

Just setting the message in onInvalid leaves the form stuck even after correcting the input
To change the message, pass a string to setCustomValidity() on the input. When a form is submitted, an invalid event fires on each field that fails its check, so React can receive it with onInvalid. The React <input> reference describes onInvalid as the event handler called when an input fails validation on submit.
At first, I created a form that only sets the message in onInvalid:
import { useState, type FormEvent } from 'react';
// A form that only sets the message in onInvalid and never clears it
export function OnlyInvalidForm() {
const [email, setEmail] = useState('');
const [result, setResult] = useState('');
function handleSubmit(e: FormEvent<HTMLFormElement>) {
e.preventDefault();
setResult(`送信しました:${email}`);
}
return (
<form onSubmit={handleSubmit}>
<label>
メールアドレス
<input
type="email"
required
value={email}
onChange={(e) => setEmail(e.target.value)}
onInvalid={(e) => e.currentTarget.setCustomValidity('メールアドレスを入力してください')}
/>
</label>
<button type="submit">登録する</button>
<output>{result}</output>
</form>
);
}
Submitting with an empty field now showed the message in Japanese. However, after I corrected the input to "neko@example.com" and submitted again, the same message still appeared and the form was not submitted. The following record shows the results of each submission.
--- Submit while empty
メールアドレス: value="" valid=false [valueMissing,customError] message="メールアドレスを入力してください"
--- "neko" で送信
メールアドレス: value="neko" valid=false [typeMismatch,customError] message="メールアドレスを入力してください"
--- "neko@example.com" に直して送信
メールアドレス: value="neko@example.com" valid=false [customError] message="メールアドレスを入力してください"
output=""

In the last line, valueMissing and typeMismatch have both cleared, but customError remains and valid=false. Passing a non-empty string to setCustomValidity() puts the field into a "custom error" state, and it stays that way until you pass an empty string. MDN's description of setCustomValidity() also says to pass an empty string when there is no error, and that while the message is non-empty, the form fails validation and is not submitted.
There was another problem. When I entered "neko" and submitted, the Japanese message meaning "Please enter your email address" was shown. The field already had input, so telling the user to enter it doesn't say what to fix. The message has to change depending on the kind of mistake.
Clear on input change, and choose the message on submit
In the corrected version, I separated two jobs:
onChange: clear the message withsetCustomValidity('')every time the input changesonInvalid: when submitting fails the check, look atvalidityand set the matching message
I put the logic that picks the message into a function. messages takes pairs of validity flag names and the message to show for each.
// Names of the ValidityState flags that are set for each input rule
type ValidityKey = Exclude<keyof ValidityState, 'valid' | 'customError'>;
export type Messages = Partial<Record<ValidityKey, string>>;
// Look at the input's state and pass the matching message to setCustomValidity
export function setJapaneseMessage(el: HTMLInputElement, messages: Messages) {
el.setCustomValidity(''); // Clear the previous message and return to the native check result
const key = (Object.keys(messages) as ValidityKey[]).find((k) => el.validity[k]);
if (key) el.setCustomValidity(messages[key] ?? '');
}
If the failed check is for a flag that is not listed in messages, nothing is set, so the browser's default message appears. This function also checks the flags in the order they appear in messages and uses the first match. If several flags match, put the message you want to prefer first.
Call this function from inside the input component:
import type { ComponentProps } from 'react';
import { setJapaneseMessage, type Messages } from './japaneseMessage';
type FieldProps = ComponentProps<'input'> & { label: string; messages: Messages };
export function Field({ label, messages, onChange, ...props }: FieldProps) {
return (
<label>
{label}
<input
{...props}
onInvalid={(e) => setJapaneseMessage(e.currentTarget, messages)}
onChange={(e) => {
e.currentTarget.setCustomValidity(''); // Clear the message when the input changes
onChange?.(e);
}}
/>
</label>
);
}
In the form, you write the input rules and messages for each field. The input rules stay as the HTML attributes required, type="email", pattern, and minLength.
import { useState, type FormEvent } from 'react';
import { Field } from './Field';
export function SignupForm() {
const [email, setEmail] = useState('');
const [zip, setZip] = useState('');
const [nickname, setNickname] = useState('');
const [result, setResult] = useState('');
function handleSubmit(e: FormEvent<HTMLFormElement>) {
e.preventDefault();
setResult(`送信しました:${email} / ${zip} / ${nickname}`);
}
return (
<form onSubmit={handleSubmit}>
<Field
label="メールアドレス"
type="email"
required
value={email}
onChange={(e) => setEmail(e.target.value)}
messages={{
valueMissing: 'メールアドレスを入力してください',
typeMismatch: 'メールアドレスは neko@example.com のような形で入力してください',
}}
/>
<Field
label="郵便番号"
required
pattern="[0-9]{3}-[0-9]{4}"
value={zip}
onChange={(e) => setZip(e.target.value)}
messages={{
valueMissing: '郵便番号を入力してください',
patternMismatch: '郵便番号は 123-4567 のように、ハイフンを入れて入力してください',
}}
/>
<Field
label="ニックネーム"
required
minLength={2}
value={nickname}
onChange={(e) => setNickname(e.target.value)}
messages={{
valueMissing: 'ニックネームを入力してください',
tooShort: 'ニックネームは2文字以上で入力してください',
}}
/>
<button type="submit">登録する</button>
<output>{result}</output>
</form>
);
}
The message changed depending on the mistake
I entered wrong values, pressed submit, and recorded each field's validity and validationMessage (the message shown for that field). Each record includes only the lines relevant to the point.
Submitting with everything empty put a "please enter…" message on all three fields. In the Chromium used for testing, only the first email field showed a speech bubble. As described in MDN's invalid event description, however, invalid fires on every field that fails its check when the form is submitted.
--- Submit while empty
メールアドレス: value="" valid=false [valueMissing,customError] message="メールアドレスを入力してください"
郵便番号: value="" valid=false [valueMissing,customError] message="郵便番号を入力してください"
ニックネーム: value="" valid=false [valueMissing,customError] message="ニックネームを入力してください"
Right after I entered "neko" in the email field, onChange had cleared the message. So customError was gone, and validationMessage had returned to the browser's English. When I submitted, the Japanese message for typeMismatch was set.
--- メールアドレスに "neko" と入力した直後
メールアドレス: value="neko" valid=false [typeMismatch] message="Please include an '@' in the email address. 'neko' is missing an '@'."
--- "neko" で送信
メールアドレス: value="neko" valid=false [typeMismatch,customError] message="メールアドレスは neko@example.com のような形で入力してください"
Next, I corrected the email to "neko@example.com" and then tried the postal code and the nickname. Each got a message that matched its mistake. The email field, which I had already fixed, returned to valid=true.
--- 郵便番号を "1234567" にして送信
メールアドレス: value="neko@example.com" valid=true [] message=""
郵便番号: value="1234567" valid=false [patternMismatch,customError] message="郵便番号は 123-4567 のように、ハイフンを入れて入力してください"
--- ニックネームを "ね" にして送信
ニックネーム: value="ね" valid=false [tooShort,customError] message="ニックネームは2文字以上で入力してください"
--- ニックネームを "ねこ" にして送信
メールアドレス: value="neko@example.com" valid=true [] message=""
郵便番号: value="123-4567" valid=true [] message=""
ニックネーム: value="ねこ" valid=true [] message=""
output="送信しました:neko@example.com / 123-4567 / ねこ"
When every field was corrected, onSubmit was called and the form was submitted.
Which flags to look at
The flag names used in messages come from MDN's ValidityState description. This article uses the following four:
| Flag | Becomes true when |
Corresponding attribute |
|---|---|---|
valueMissing |
A required field is empty | required |
typeMismatch |
The value is not in email or URL format | type="email", type="url" |
patternMismatch |
The value does not match pattern |
pattern |
tooShort |
The value is shorter than the minlength character count |
minlength (minLength in React) |
When the email field was empty, valueMissing was the only input-rule flag set. typeMismatch was not set. This is why "missing" and "wrong format" can be shown as different messages.
Be careful with tooShort. According to MDN's minlength description, the minlength check runs only when the user changes the value. Putting a short string into value from code does not trigger tooShort. For this reason, I entered the text one character at a time with the keyboard during testing.





