React · Lesson 29 of 120
Validation
Showing errors.
Users make mistakes. Good forms check the input, and explain exactly what's wrong, right next to the field.
- Users make mistakes
- Check the input
- Explain clearly
Checking an email
Validate returns an error message, or an empty string. On submit, we store that error. If it's empty, we accept the email. The message appears under the input. We submit an email with no at sign. Run it.
App.jsxjsx
import { useState } from "react";
const validate = email => (email.includes("@") ? "" : "Please enter a valid email address");
export default function App() {
const [email, setEmail] = useState("");
const [error, setError] = useState("");
const [done, setDone] = useState(false);
function handleSubmit(e) {
e.preventDefault();
const message = validate(email);
setError(message);
setDone(message === "");
}
return (
<form onSubmit={handleSubmit}>
<input id="email" value={email} onChange={e => setEmail(e.target.value)} /> <button>Join</button>
{error && <small>{error}</small>}{done && <p>Thanks for joining!</p>}
</form>
);
}Also uses style.css
body{font-family:-apple-system,Helvetica,Arial,sans-serif;margin:22px;font-size:21px;color:#1d1d1f;background:#fafafa}
h1{font-size:34px;margin:0 0 14px} h2{font-size:26px;margin:0 0 10px}
button{font-size:19px;padding:9px 18px;border-radius:9px;border:0;background:#61dafb;color:#111;font-weight:600;margin:4px 6px 4px 0}
input{font-size:19px;padding:8px 10px;border:2px solid #bbb;border-radius:8px}
li{margin:5px 0} .box{padding:14px;border-radius:12px;background:#fff;border:2px solid #ddd;margin:8px 0}
.done{text-decoration:line-through;color:#999} small{color:crimson;display:block;font-size:16px} .big{font-size:64px;font-weight:800}Also uses actions.json
[{"type": "#email", "text": "priya.example.com"}, {"key": "Enter"}]Summary
Validate on submit, store the error in state, and show it next to the field. Next, practice with a signup form.
Key takeaways- validate()
- error state
- {error && ...}
Next up: Practice: A Signup Form — forms together