Created
June 5, 2021 11:00
-
-
Save isaacssemugenyi/9ac28ead49a691f8984c56e554590841 to your computer and use it in GitHub Desktop.
Full code
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<template> | |
<div class="row"> | |
<div class="offset-md-3 col-md-6 mt-5"> | |
<h3>Article Form</h3> | |
<form action="#" @submit.prevent="submitData"> | |
<div class="form-group"> | |
<input | |
type="text" | |
class="form-control" | |
placeholder="Title" | |
v-model="article.title" | |
@blur="validate('title')" | |
@keypress="validate('title')" | |
/> | |
<p | |
class="errors" | |
v-if="!!errors.title" | |
>{{errors.title}}</p> | |
</div> | |
<div class="form-group"> | |
<textarea | |
type="text" | |
class="form-control" | |
placeholder="description" | |
v-model="article.description" | |
@blur="validate('description')" | |
@keypress="validate('description')" | |
></textarea> | |
<p | |
class="errors" | |
v-if="!!errors.description" | |
>{{errors.description}}</p> | |
</div> | |
<div class="form-group"> | |
<input type="submit" class="btn btn-primary btn-block" value="submit" /> | |
</div> | |
</form> | |
</div> | |
</div> | |
</template> | |
<script> | |
import * as Yup from "yup"; | |
const ArticleSchema = Yup.object().shape({ | |
title: Yup.string() | |
.min(10, "Title should be less than 10 characters") | |
.max(100, "Title should not exceed 100 characters") | |
.required("Title is required"), | |
description: Yup.string() | |
.min(50, "Description should be less than 50 characters") | |
.max(1000, "Description should not exceed 1000 characters") | |
.required("Description is required"), | |
}); | |
export default { | |
name: "ArticleForm", | |
data() { | |
return { | |
article: { | |
title: "", | |
description: "", | |
}, | |
errors: { | |
title: "", | |
description: "", | |
}, | |
}; | |
}, | |
methods: { | |
submitData() { | |
ArticleSchema.validate(this.article, { abortEarly: false }) | |
.then(() => { | |
const submittedData = `${this.article.title} ${this.article.description}`; | |
alert(submittedData); | |
}) | |
.catch((err) => { | |
err.inner.forEach((error) => { | |
this.errors = { ...this.errors, [error.path]: error.message }; | |
}); | |
}); | |
}, | |
validate(field) { | |
ArticleSchema.validateAt(field, this.article) | |
.then(() => (this.errors[field] = "")) | |
.catch((err) => { | |
this.errors[err.path] = err.message; | |
}); | |
}, | |
} | |
}; | |
</script> | |
<style scoped> | |
.errors { | |
color: red; | |
} | |
</style> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment