Skip to content

Instantly share code, notes, and snippets.

@boonyasukd
Last active June 23, 2019 00:05
Show Gist options
  • Save boonyasukd/9b1fb8aaf6da88179e16786d871b55a6 to your computer and use it in GitHub Desktop.
Save boonyasukd/9b1fb8aaf6da88179e16786d871b55a6 to your computer and use it in GitHub Desktop.
<script>
import { state } from 'vue';
import { setValidation } from './validator';
export default {
setup() {
const validationRules = {
firstName: 'required|alpha_spaces|min:3|max:16',
lastName: 'required|alpha_spaces|min:3|max:16',
address: 'min:6|max:128',
phoneNum: 'numeric|length:10',
email: 'required|email',
};
const userModel = state({
firstName: null,
lastName: null,
address: null,
phoneNum: null,
email: null,
});
// function to simply keep watching/validating model's fields against rules,
// and return validation result as reactive fields
const { isModelValid, errorMsgs } = setValidation(userModel, validationRules);
submitForm() {
if (isModelValid) {
// submit data to server
}
}
return { userModel, submitForm, errorMsgs };
},
};
</script>
<template>
<form id="user-detail-form">
<label>First Name:</label>
<input id="user-firstName" v-model="userModel.firstName" />
<div class="form-field-error" v-show="errorMsgs['firstName']">{{ errorMsgs['firstName'] }}</div>
...
<button @click="submitForm">Submit</button>
</form>
</template>
import { watch, value } from 'vue';
import { Validator } from 'Validator';
function setValidation(model, rules) {
const isModelValid = value(true);
const errorMsgs = value([]);
const validateAll = () => {
const v = Validator.make(model, rules);
isModelValid.value = v.passes();
errorMsgs.value = v.getErrors();
};
for (const prop in rules) {
watch(() => model[prop], validateAll);
}
return { isModelValid, errorMsgs };
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment