javascript / beginner
Snippet
Validating Numeric Input Bounds with Try Catch and Custom Errors in Vue
JavaScript's try...catch block combined with the throw statement allows you to enforce domain rules by interrupting execution when invalid data is encountered. In Vue, catching custom Error instances provides a clean way to populate UI validation messages.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<script setup>import { ref } from 'vue';const ageInput = ref('');const errorMessage = ref('');function validateAge() {errorMessage.value = '';try {const age = Number(ageInput.value);if (Number.isNaN(age) || age < 18) {throw new Error('Age must be a valid number of at least 18.');}} catch (err) {errorMessage.value = err.message;}}</script>
vue
Breakdown
1
errorMessage.value = '';
Clears any existing error message before starting the validation attempt.
2
throw new Error('Age must be a valid number of at least 18.');
Creates and throws a custom JavaScript Error object if the input fails the criteria.
3
catch (err) {
errorMessage.value = err.message;
}
Catches the thrown error and assigns its message string to the reactive error ref.