0 day streak
javascript / intermediate
Snippet

Structured Form Validation via Regex Pattern Matching and Object Destructuring

Modern JavaScript features such as `Object.entries()`, nested parameter destructuring, nullish coalescing (`??`), and RegExp testing enable clear, maintainable data validation routines. Reactive error maps in Vue instantly reflect validation states back to template bindings.

snippet.js
javascript
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
import { reactive } from 'vue';
export function useFormValidator(rules) {
const validationErrors = reactive({});
function validatePayload(formData) {
Object.keys(validationErrors).forEach(key => delete validationErrors[key]);
for (const [field, { pattern, required, minLength }] of Object.entries(rules)) {
const value = formData[field] ?? '';
const trimmed = typeof value === 'string' ? value.trim() : '';
if (required && trimmed.length === 0) {
validationErrors[field] = 'Field is required';
continue;
}
if (minLength && trimmed.length < minLength) {
validationErrors[field] = `Must be at least ${minLength} characters`;
continue;
}
if (pattern && !pattern.test(trimmed)) {
validationErrors[field] = 'Invalid format';
}
}
return Object.keys(validationErrors).length === 0;
}
return { validationErrors, validatePayload };
}
vue
Breakdown
1
for (const [field, { pattern, required, minLength }] of Object.entries(rules)) {
Uses Object.entries with nested object destructuring to extract both rule keys and individual validation criteria.
2
const value = formData[field] ?? '';
Applies the nullish coalescing operator to supply a safe fallback string when a field is undefined or null.
3
if (pattern && !pattern.test(trimmed)) {
Executes RegExp.prototype.test against the trimmed value to verify regex conformity.