-
Notifications
You must be signed in to change notification settings - Fork 0
/
App.vue
87 lines (82 loc) · 2.09 KB
/
App.vue
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
<template>
<h1>
Vue Form Validator
</h1>
<form novalidate @submit="onSubmit">
<div>
<label for="usernameInput">
Input with custom validation ('admin' username invalid)
</label>
<input
id="usernameInput"
ref="usernameInputRef"
v-model="username"
:minlength="3"
@invalid="usernameValidator.onInvalid"
>
<div v-if="usernameValidator.getInvalidMessage()" style="color: red;">
{{ usernameValidator.getInvalidMessage() }}
</div>
</div>
<div>
<label for="postalCodeInput">
Input with native (required) validation
</label>
<input
id="postalCodeInput"
ref="postalCodeInputRef"
v-model="postalCode"
type="text"
required
@invalid="postalCodeValidator.onInvalid"
>
<div v-if="postalCodeValidator.getInvalidMessage()" style="color: red;">
{{ postalCodeValidator.getInvalidMessage() }}
</div>
</div>
<button type="submit">
Submit
</button>
</form>
</template>
<script lang="ts">
import { useValidator } from '../src'
import { ref, defineComponent } from 'vue'
export default defineComponent({
name: 'App',
setup() {
const usernameInputRef = ref(null)
const postalCodeInputRef = ref(null)
const usernameValidator = useValidator(usernameInputRef)
const postalCodeValidator = useValidator(postalCodeInputRef)
return {
usernameInputRef,
postalCodeInputRef,
usernameValidator,
postalCodeValidator,
}
},
data() {
return {
username: '',
postalCode: '',
}
},
methods: {
onSubmit(event : Event): void {
event.preventDefault()
if (this.username === 'admin') {
this.usernameValidator.setCustomError('Username is already taken')
} else {
this.usernameValidator.setCustomError(null)
}
const target = event.target as HTMLFormElement
if (!target.checkValidity()) {
console.log('validation failed')
return
}
console.log('submit success')
},
},
})
</script>