This article provides you with the first experience of writing the simple basic Form
. After that, we will show you how to do the simple validation and cover some of writing the CSS
on this lightweight Form
. We will cover all these things with some code snippets.
What is WebAtoms?
WebAtoms
is an advanced MVVM framework to write cross-platform applications in HTML5 and Xamarin.Forms.
Why do we Need a Form?
A Form
is the most vital aspect of the user-application interaction for gathering input from the user and storing it in the database.
A Form should contain basic validation to collect valid and accurate data from the user to provide a seamless experience for the user.
What is WebAtoms Form?
Earlier in the WebAtoms
, we have defined the AtomForm
as a class component. To validate the AtomForm
, we have isolated the logic and validation part to the ViewModel
section.
We will guide you on how to write the simple Form
using the WebAtoms Form
component.
Form
and FormField
are javaScript functional components, they are nothing but simple javascript functions.
How to use the Form?
<Form>
<FormField
label="First Name"
error={Bind.oneWay(() =>
validate("first name", this.data.firstName,))}>
<input
value={Bind.twoWaysImmediate(() =>
this.data.firstName)} />
</FormField>
</Form>
How to apply multiple validations?
const validate = (label: string, value: string, r?: RegExp) => {
if (!value)
{
return `${label} is required`;
}
if (r) {
if (!r.test(value)) {
return `${label} is invalid`;
}
}
return "";
};
const validateEmail = (label: string, value: string) =>
validate(label, value, /[a-z0-9\-\.]+\@[a-z0-9\-\.]+[a-z0-9\-]+/i);
We have described the validate
function for input validation. validateEmail
function
validates the email using the regex.
Below is the simple code snippet which shows the email validation.
<FormField
label="Email Address"
error={Bind.oneWay(() => validateEmail("Email Address",
this.data.emailAddress))}>
<input
value={Bind.twoWaysImmediate(() =>
this.data.emailAddress)} />
</FormField>
In the above example, we have just displayed a couple of simple validation. In the same manner, one can achieve complicated validation.
Benefit of WebAtoms Form.
Form component is very lightweight, meaning it is simple to implement.
In large applications, there is a requirement of having small UI components like having multiple Forms in a single form, so it becomes easier to implement the validation logic either in ViewModel or in View itself.
The error, label, and class attributes of FormField components help us write the neater and cleaner UI with complex validations.
You don't need to install any separate NPM library for building the simple form.
It will improve the speed of writing the code and also reduce the number of lines of code, it becomes easier to maintain the code.
Check out this example.
Like | Comment | Save | Share |