admin管理员组

文章数量:1127084

I'm using react-final-form library for displaying forms. I am using a simple form with a text input field in React. I am utilizing the format function with formatOnBlur: true to trim the input strings.

My goal is to run validations after the string has been trimmed (i.e., after the format function has been executed).

However, I am facing an issue where validations are not triggered if I press the Enter key to submit the form.

The validations work perfectly if I type something like "react " in the input field and click on the submit button, showing the error as expected. But when I press Enter, the form submits successfully without throwing any validation errors.

Minimal Reproducer

import "./styles.css";
import { Field, Form } from "react-final-form";

export default function App() {
  const onSubmit = (values: any) => {
    alert(JSON.stringify(values));
  };

  return (
    <div className="App">
      <Form
        onSubmit={onSubmit}
        render={({ handleSubmit, submitting, values }) => (
          <form onSubmit={handleSubmit}>
            <Field
              name="firstName"
              validate={(value) =>
                ["react", "javascript"].includes(value)
                  ? "Enter some other value"
                  : undefined
              }
              format={(value?: string) => value && value.trim()}
              formatOnBlur
            >
              {({ input, meta }) => (
                <div
                  style={{
                    display: "flex",
                    flexDirection: "column",

                    alignItems: "center",
                  }}
                >
                  <label>First Name</label>
                  <input
                    {...input}
                    type="text"
                    placeholder="First Name"
                    style={{ margin: "8px" }}
                  />
                  {meta.error && meta.touched && (
                    <span style={{ color: "red" }}>{meta.error}</span>
                  )}
                </div>
              )}
            </Field>

            <div className="buttons" style={{ marginTop: "4px" }}>
              <button type="submit" disabled={submitting}>
                Submit
              </button>
            </div>
          </form>
        )}
      />
    </div>
  );
}

Expected Behavior: The form should perform validations after formatting the field and should throw an error when I press the Enter key.

Current Behavior: The form submits successfully when pressing the Enter key, bypassing validations.

Sandbox Link: You can reproduce the issue in this sandbox.

本文标签: javascriptValidation not triggered on Enter key after formatOnBlur in reactfinalformStack Overflow