Form Validation
Client-side form validation with custom error messages
Learn how to validate user input in real-time using hyperscript's conditional logic
and event handling. Build better forms with instant feedback!
validation
if/else
add/remove classes
forms
Registration Form
Requirements:
- Email must contain @ symbol
- Password must be at least 8 characters
- Password confirmation must match
Account created successfully.
Welcome aboard.
The Code
Email Validation:
<input _="on input
if my value contains '@'
add .valid to me
remove .error from me
hide #email-error
else
add .error to me
remove .valid from me
show #email-error
end" />
Password Length Check:
<input _="on input
if my value's length >= 8
add .valid to me
remove .error from me
hide #password-error
else
add .error to me
remove .valid from me
show #password-error
end" />
Password Confirmation:
<input _="on input
if my value == #password's value
add .valid to me
hide #confirm-error
else
add .error to me
show #confirm-error
end" />
Form Submission Check:
<button _="on click
if #email's value contains '@' and
#password's value's length >= 8 and
#confirm's value == #password's value
show #success
hide #signup-form
else
log 'Form has validation errors'
end">
Submit
</button>
How it works:
on input - Validates as user types for instant feedback
if/else/end - Conditional logic for validation rules
my value contains '@' - String matching for email
my value's length >= 8 - Length validation for password
#password's value - Access other input values
add .valid / .error - Visual feedback with CSS classes
show/hide - Toggle error messages
Key Concepts:
- Real-time Validation: Immediate feedback as user types
- Conditional Logic:
if/else/end blocks for branching
- String Operations:
contains, length, equality
- Cross-field Validation: Compare multiple inputs
- Visual Feedback: CSS classes for valid/invalid states
- Compound Conditions:
and operator for multiple checks
Validation Patterns:
- Required Fields:
if my value's length > 0
- Email Format:
contains '@' (basic check)
- Length Requirements:
my value's length >= N
- Pattern Matching:
matches /regex/ (advanced)
- Field Equality:
#field1's value == #field2's value
- Numeric Ranges:
my value >= min and my value <= max
Advanced Validation Examples:
<input _="on input
if my value matches /^\d{3}-\d{3}-\d{4}$/
add .valid
else
add .error
end" />
<input type="number" _="on input
if my value >= 18 and my value <= 100
add .valid
else
add .error
end" />
<input type="checkbox" _="on change
if my checked
enable #submit-btn
else
disable #submit-btn
end" />
Try it yourself:
- Add more validation rules (username length, special characters, etc.)
- Create a password strength meter
- Add regex validation for phone numbers or zip codes
- Implement debounced validation (wait for user to stop typing)
- Add server-side validation with fetch