If you followed the getting started article, you now know how to setup the dataform and edit an object's properties. Sometimes you may need to validate if the user's input follows some requirements - for example, not leave an empty field in a registration form or provide a valid email. This article will show you how to use the validators in
You can choose when the validation of the changes happens by changing the data form's
validationMode property. Here are the available validation modes:
- Immediate - this is the default mode; all changes are validated immediately when the editor value is changed;
- OnLostFocus - the changes are validated when another editor gets focused;
Manual - the changes are validated only when the
commitAllmethod of data form is called;
Note that changes will not be committed if the validation fails.
The data form provides the following validators that you can use to validate the properties of your object:
NonEmptyValidator- validates that the field is not empty;
RangeValidator- validates that the entered value falls into the range specified by the minimum and maximum properties;
MinimumLengthValidator- validates that the entered text is no shorter that the value specified by the length property;
MaximumLengthValidator- validates that the entered text is no longer that the value specified by the length property;
EmailValidator- validates that the entered value is an email;
PhoneValidator- validates that the entered value is a phone number;
The image in the beginning of the article demonstrates the
MinimumLengthValidator for a property of type password. Here's the code to add the validator:
<df:EntityProperty name="password" index="1" > <df:EntityProperty.editor> <df:PropertyEditor type="Password" /> </df:EntityProperty.editor> <df:EntityProperty.validators> <df:MinimumLengthValidator errorMessage="Password must be at least 6 characters long." length="6" /> </df:EntityProperty.validators> </df:EntityProperty>
Want to see this scenario in action?
Check our SDK examples repo on GitHub. You will find this and many other practical examples with NativeScript UI.
Related articles you might find useful: