Advanced — Custom Validators

Compose your own validation functions using the same return format.

// A custom validator follows the same signature as built-in ones
function isSpanishPhone(value) {
    const regex = /^(\+34|0034|34)?[6789]\d{8}$/
    return {
        isValid: regex.test(value.replace(/\s/g, '')),
        errorMessage: 'Please enter a valid Spanish phone number'
    }
}

// Use it like any other validator
const result = isSpanishPhone(phoneInput.value)

if (result.isValid) {
    phoneWrapper.classList.remove('c--form-input-a--error')
    phoneWrapper.classList.add('c--form-input-a--valid')
    phoneError.textContent = ''
} else {
    phoneWrapper.classList.add('c--form-input-a--error')
    phoneWrapper.classList.remove('c--form-input-a--valid')
    phoneError.textContent = result.errorMessage
}
Playground