Adding validation when you code up webforms in Alpas
Adam Miedema
Posted on May 27, 2020
When you’re coding up a website, chances are, you’ll end up adding a form sooner or later. Whether it’s for a simple email newsletter signup, a registration form, or a contact form, webforms will likely make an appearance. And, you’ll probably be wanting to validate the entries users are typing in before writing to your database.
With the Alpas web framework, validation is one of the many batteries-included features available to you.
In the Alpas backend, when you are calling the form data over http, you can apply a set of pre-configured rules.
Let’s look at the following example:
fun create(call: HttpCall) {
call.applyRules("email", failfast = true) {
required()
max(100) { attr, value -> val len = value?.toString()?.length "$attr is $len characters long. It should be no more than 32."
}
email()
unique("emails")
}.validate()
There are some pretty cool and convenient things going on this small example.
- You can list out rules you want to apply to the email field validation using
call.applyRules()
and passing the form key to apply the rules to - Adding
failfast
and setting it totrue
will stop validation on first fail; convenient for saving additional processing time and quickly getting an error in front of the user - You can make a form field required
- You can set a max character limit (also a min)
- All of the validation comes with default error sent back to the front-end, in which you can easily update the message as shown
- You can validate an email address against RFC 2822 standards
- You can ensure an entry is unique within a database table column
These are just some of the many default validation rules you can apply. Check out the documentation for more examples and out-of-the-box validation.
Looking to customize your own validation rules? No problemo!
I’ll show you how you can customize validations in the next post. 👍
Posted on May 27, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.