I have a Xamarin.Form app, and I am consuming an ASP.Net Web WebAPI with Model State for validation in my internal models. If I got a "bad request" my API return this JSON object:
{
message: 'The request is invalid.',
modelState: {
model.**Name**: [
"The name is empty"
]
}
}
So, I want to simplify my work in the UI to read that result, my question are: How can I do to use this object for display the error in my UI? or Does Xamarin Form have any helper like to ASP.NET MVC Validator @Html.ValidationMessageFor(model => model.Name), it could display automatic the error in the UI?
Thanks!
答案 0 :(得分:1)
You can create behaviors for controls like the below one
public class EmailValidatorBehavior : Behavior<Entry>
{
const string emailRegex = @"^(?("")("".+?(?<!\\)""@)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])@))" +
@"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-\w]*[0-9a-z]*\.)+[a-z0-9][\-a-z0-9]{0,22}[a-z0-9]))$";
protected override void OnAttachedTo(Entry bindable)
{
bindable.TextChanged += HandleTextChanged;
base.OnAttachedTo(bindable);
}
void HandleTextChanged(object sender, TextChangedEventArgs e)
{
bool IsValid = false;
IsValid = (Regex.IsMatch(e.NewTextValue, emailRegex, RegexOptions.IgnoreCase, TimeSpan.FromMilliseconds(250)));
((Entry)sender).TextColor = IsValid ? Color.Default : Color.Red;
}
protected override void OnDetachingFrom(Entry bindable)
{
bindable.TextChanged -= HandleTextChanged;
base.OnDetachingFrom(bindable);
}
}
Use this behavior in XAML as below
Add namespace for your behavior
xmlns:local="clr-namespace:Mynamespace.Behaviors"
Add behavior to the entry
<Entry x:Name="txtEmail" Placeholder="Enter Your Password" >
<Entry.Behaviors>
<local:EmailValidatorBehavior />
</Entry.Behaviors>
</Entry>
The above behavior will validate email and change the textbox color ro red if the email is not valid. Like that you can create more behaviours