skip to Main Content

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


  1. Chosen as BEST ANSWER

    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.


  2. 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:

    <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)."
      required
    />
    

    Adding required will enforce the pattern check upon form submission. Let me know if it works.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search