I have a clean install of Next.js 13.
npx create-next-app@latest footest
I’m creating a single file app/footest/page.tsx
.
export default function Page() {
return (
<div>
<form action="/action_page.php">
<label htmlFor="pswrd">Password:</label>
<input
type="password"
id="pswrd"
name="pswrd"
pattern="[a-z0-9]{1,15}"
title="Password should be digits (0 to 9) or alphabets (a to z)."
/>
<button type="submit">Submit</button>
</form>
</div>
)
}
When I load the page in my browser (latest Chrome), it lets me submit the page without matching the specified pattern. The w3schools pattern example works fine. The example I’m providing is taken directly from the next.js docs.
2
Answers
The behavior is slightly different between the Codepen and Next.js. The Next.js will allow you to submit an empty form, but the Codepen will not. I was misreading the pattern which was causing an issue when testing against strings.
The Pattern attribute is used for validation, but it will only prevent form submission if the input also has a
required
attribute. Update your input tag:Adding required will enforce the pattern check upon form submission. Let me know if it works.