Form Validation के Basics
Validate करने का मतलब है user के type करते वक्त values check करना और submit करने से पहले helpful messages दिखाना।
In this page:
Syntax
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
<!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. #}
आम गलतियां
- सिर्फ client-side validation पर trust करना
- user के type करने से पहले errors दिखाना
- 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: