← Back to Vue.js Course | Chapter 5: Forms | Lesson 4 of 6

Form Validation के Basics

Validate करने का मतलब है user के type करते वक्त values check करना और submit करने से पहले helpful messages दिखाना।

In this page:

  1. Form Validation Basics
Syntax
markup
export default {
  computed: {
    error() {
      return this.field ? '' : 'error message';
    }
  }
}

<p v-if="error">{{ error }}</p>

Form Validation Basics

एक simple approach ऐसे computed properties इस्तेमाल करता है जो current data के आधार पर error messages return करते हैं, और जब तक errors हों submit button disable करते हैं।

Complex forms के लिए VeeValidate या Vuelidate जैसी libraries consider करें। हमेशा server पर फिर से validate करें।

Note: Client-side validation user experience के लिए है; server को अभी भी validate करना चाहिए।

उदाहरण: Form validation basics

markup
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
</head>
<body>
<div id="app">
  <input v-model="email" placeholder="email">
  <span style="color:red">{{ error }}</span>
  <button :disabled="!!error">Sign up</button>
</div>
<script>
  Vue.createApp({
    data() { return { email: "" }; },
    computed: {
      error() {
        if (!this.email) return "Email is required";
        return /^\S+@\S+\.\S+$/.test(this.email) ? "" : "Enter a valid email";
      },
    },
  }).mount("#app");
  const i = document.querySelector("input");
  i.value = "[email protected]"; i.dispatchEvent(new window.Event("input"));
  Vue.nextTick(() => console.log("valid email -> button disabled:", document.querySelector("button").disabled));
</script>
</body>
</html>

<!-- Output:
Rendered: Sign up
console: valid email -> button disabled: false
-->
Live Example
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. सिर्फ client-side validation पर trust करना
  2. user के type करने से पहले errors दिखाना
  3. invalid रहते submit disable न करना
चैप्टर सारांश
  • Computed properties errors produce कर सकते हैं
  • invalid रहते submit disable करें
  • बड़े forms के लिए Libraries मदद करती हैं
  • हमेशा server पर भी validate करें
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

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.