Level: beginner • Mithril.js Version: latest
bss form login m.mount validation
This example shows a login form with fields for user name and email including validation and displaying of error messages.
Type | Name | URL |
---|---|---|
script | mithril@latest | https://unpkg.com/mithril@latest |
script | bss@1.2.8 | https://unpkg.com/bss@1.2.8 |
import b from 'bss'
const username = {
label: 'username',
value: '',
error: ''
}
const email = {
label: 'email',
value: '',
error: ''
}
const input = (attrs) =>
m('label' + b.d('flex').m(8),
m('span' + b.w(100), attrs.label),
m('input', {
value: attrs.value,
oninput: e => {
attrs.value = e.target.value
attrs.error && validate()
}
}),
attrs.error && m('span' + b.c('white').bc('tomato'), attrs.error)
)
const validate = () => {
username.error = username.value.length < 4
&& 'Please enter a username longer than 4 characters'
email.error = !email.value.match(/.+@.+\..+/)
&& 'Please enter a valid email'
}
const onsubmit = e => {
e.preventDefault()
validate()
if (username.error || email.error)
return true
alert('Hello ' + username.value + ' i will spam you at ' + email.value)
}
m.mount(document.body, {
view: () =>
m('form', {
onsubmit,
},
input(username),
input(email),
m('button', 'submit')
)
})
As a prerequisite for this snippet, the latest version of Mithril.js framework is required. Beginners should have no problems following this example, that simply shows some basic recipies.
In this code sample Mithril.js' m.mount
API method is use, besides the basic hyperscript function m().
The example was written by smuemd, last edits were made on 16 October 2021.
Did you note a typo or something else? So let me know by opening an issue. Or much better: just fork the repository on GitHub, push your commits and send a pull request. Ready to start your work? Then click on the edit link below. Thanks in advance!