I have a UWP app that uses various TextBox
to collect user information:
<Grid>
<TextBox Text="{Binding Codigo}"></TextBox>
<TextBox Text="{Binding Producto}"></TextBox>
<TextBox Text="{Binding Cantidad}"></TextBox>
</Grid>
My question, what is the best way to validate that the user does not enter incorrect data, that is, make them TextBox
only allow numbers to be entered or some kind of character mask?
Must be done from code or can be done from XAML
Currently
UWP
it does not incorporate any validation framework, however the C# community is thriving and on GitHub there is already a very interesting alternative that is worth reviewing: ValidatableBase To use it you must download the code from GitHub and compile the library to then add it to the solution .The model
what you should do is create a model that inherits from
ValidatableBase
, since you are probably using it,BindableBase
you should use something like thisThe viewModel
To trigger the validation you can do it in many ways, but one way is with a button, in which case it is convenient to have a ViewModel like this.
XAML and binding
The
XAML
one you should bind with is like thisAdding validation attributes to model properties
Once you have everything ready then you decorate the model with validation attributes, I have included in the example validation of the required field and validation that the email value is in fact an email, making use of a custom validation.
Processing the errors in the ViewModel
Finally in the Viewmodel implement the method
Execute
so that it puts you inErrores
all the errors of all the properties of the model, being like thisThat will work for you.
UWP - How to implement field validation in Universal Apps
You could make use of DataAnnotations , adding the reference to
System.ComponentModel.DataAnnotations
Basically, you
ViewModel
define the attribute on the property that you bind to the control in the view:For more detail I recommend this article Validation in MVVM using Data Annotations , it is very complete
Because it is a UWP application, perhaps the DataAnnotations library will not let you reference it, but following the same path there is an alternative with:
It's basically the same, you define validation attributes in the properties of the
ViewModel
, only you would use an implementation suitable for WinRT.