A good UX practice when developing applications that involve filling a form is to give feedback to the user when a field is wrong or invalid.
In this article, we are going to do just that by highlighting the fields where user input is invalid so that they know where exactly is the input issue.
The result of this entry validation will be something like this:
As you can above I’m highlighting the border of the entry with a different color and also changing the placeholder to show a message related to the input error.
Let’s code step by step
1-Create a Custom Entry Control
The first I’m going to do is to create a new control that inherits from Entry and will add three properties:
- IsBorderErrorVisible: To show when the error would be visible
- BorderErrorColor: The border color of the entry
- ErrorText: Text error to show in the placeholder
2-Create custom renderers per platform
As you know the Xamarin Forms Entry does not provide a property for customizing the border color, so to achieve this we are going to create a custom renderer.
As you can see above, the code is simple, when the property IsBorderErrorVisible change I’m setting the border color to the native control color and if not I’m using the default light entry color that the entries have in the border.
In Android, the code is logic is similar to IOS, but here we are going to update the border also in the method OnElementChanged because the default Android entry does not have a border, and I want to change the default entry to have a light gray border.
3-Create an Entry Behavior
In this behavior, we will handle the error to provide ui feedback to the user when validation occurs
As you can see here, in the method OnPropertyChanged and changing the color to the PlaceHolder and also assigning the Text Error. Also, I’m setting the IsBorderErrorVisible to false each time the user types a text on the field.
4-Use the control
The User model is really simple, each property instead of being a simple string field will be a Field which will have three new properties to handle errors (Name- IsNotValid – NotValidMessageError) .
Each time the user clicks on the button, I’m raising the method OnValidationCommand to do the validations and assign to each property in the model if there’s an error and the kind of error found.
For example, if (User.Password.Name.Length < 5), I’m assigning to the field Password into the property Message the text “Password must have more than 5 characters” and setting NotValid to true.
NOTE: Another option to achieve this is instead of creating an Entry behavior handle the logic of the placeholder in each renderer, I didn’t do that to have more flexibility on adding/removing this behavior easily to my entry fields.
- Fody.PropertyChanged: To handle property change
And that’s all, you can check the full source code here: