← Back to React Course | Chapter 7: Forms & User Input | Lesson 3 of 8

Client-Side Form Validation करना

Form validation एक teacher आपका homework accept करने से पहले check करने जैसा है, अगर कुछ गलत हो तो exactly बताते हुए कि क्या fix करना है।
Syntax
markup
function validate(values) {
  const errors = {};
  if (!values.field) errors.field = "Error message";
  return errors;
}

const errors = validate(values);
<button disabled={Object.keys(errors).length > 0}>Submit</button>

एक Simple Validation Function लिखना

एक validation function current form values लेता है और एक object return करता है जो describe करता है कि क्या गलत है, अगर कुछ हो। Validation logic को एक plain function में रखना (JSX से अलग) इसे test और reuse करना आसान बनाता है।

Note: जब सब कुछ valid हो तो एक empty object (कोई errors नहीं) return करें, ताकि 'Object.keys(errors).length === 0' का मतलब हो कि form valid है।
Warning: Validation logic को सीधे JSX के अंदर न डालें — यह पढ़ना मुश्किल और reuse करना impossible हो जाता है।

उदाहरण: Writing a Simple Validation Function

markup
<!DOCTYPE html>
<html>
<head>
  <script src="https://unpkg.com/react@18/umd/react.development.js"></script>
  <script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
  <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
</head>
<body>
  <div id="root"></div>
  <script type="text/babel">
function validate(email) {
  if (!email) return "Email is required";
  if (!email.includes("@")) return "Email must contain @";
  return "";
}
function App() {
  const [email, setEmail] = React.useState("");
  const error = validate(email);
  return <div><input value={email} onChange={e => setEmail(e.target.value)} /><p style={{color: "red"}}>{error}</p></div>;
}
ReactDOM.createRoot(document.getElementById('root')).render(<App />);
  </script>
</body>
</html>

Field Touch होने के बाद ही Errors दिखाना

User के कुछ भी type करने से पहले 'Email is required' दिखाना aggressive लगता है। Per field एक touched state track करना, blur पर true set किया जाता है, आपको errors दिखाना तब तक delay करने देता है जब तक user ने असल में उस field के साथ interact न किया हो।

Note: onBlur (जब एक field focus खोता है तब fire होता है) एक field को touched mark करने की standard जगह है।
Warning: Error दिखाने से पहले touched check करना भूल जाने का मतलब है हर field user के कुछ करने से पहले लाल दिखता है।

उदाहरण: Showing Errors Only After the Field Is Touched

markup
<!DOCTYPE html>
<html>
<head>
  <script src="https://unpkg.com/react@18/umd/react.development.js"></script>
  <script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
  <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
</head>
<body>
  <div id="root"></div>
  <script type="text/babel">
function App() {
  const [email, setEmail] = React.useState("");
  const [touched, setTouched] = React.useState(false);
  const error = !email ? "Email is required" : "";
  return (
    <div>
      <input value={email} onChange={e => setEmail(e.target.value)} onBlur={() => setTouched(true)} />
      {touched && <p style={{color: "red"}}>{error}</p>}
    </div>
  );
}
ReactDOM.createRoot(document.getElementById('root')).render(<App />);
  </script>
</body>
</html>

Form Valid होने तक Submit Disable करना

एक submit button का disabled prop सीधे इससे जोड़ा जा सकता है कि form में currently errors हैं या नहीं। यह एक immediate visual signal देता है और invalid submissions को पूरी तरह रोकता है, सिर्फ एक error message पर relying करने के बजाय।

Note: इसे touch पर errors दिखाने के साथ combine करें ताकि button disabled होना user को mysterious न लगे।
Warning: Button disable करना server-side validation का substitute नहीं है — हमेशा backend पर भी re-validate करें।

उदाहरण: Disabling Submit Until the Form Is Valid

markup
<!DOCTYPE html>
<html>
<head>
  <script src="https://unpkg.com/react@18/umd/react.development.js"></script>
  <script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
  <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
</head>
<body>
  <div id="root"></div>
  <script type="text/babel">
function App() {
  const [email, setEmail] = React.useState("");
  const isValid = email.includes("@");
  return (
    <div>
      <input value={email} onChange={e => setEmail(e.target.value)} />
      <button disabled={!isValid}>Submit</button>
    </div>
  );
}
ReactDOM.createRoot(document.getElementById('root')).render(<App />);
  </script>
</body>
</html>
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. सिर्फ submit पर validate करना और user के type करते समय कभी feedback न देना।
  2. User के form को touch करने से पहले सभी error messages दिखाना।
  3. Form invalid होने पर submit button disable न करना, users को फिर भी bad data submit करने देते हुए।
चैप्टर सारांश
  • Client-side validation submission से पहले form values को rules (required, format, length) के against check करती है।
  • Validation हर change पर, blur पर, या सिर्फ submit पर run हो सकती है, हर एक अलग UX tradeoffs के साथ।
  • Form state के साथ एक errors object store करना आपको field-specific messages दिखाने देता है।
  • Validity के आधार पर submit button disable करना obviously-invalid submissions रोकता है।
ब्राउज़र सपोर्ट

कोई React-version restriction नहीं — pure JavaScript validation logic किसी भी supported React version में काम करता है।

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.