1

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!

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

Can you get me more information about this? What about of XAML?
Thank you for your answer! but I mean, I have a PLC with all model, for every model's property I have a data notations for validations in my web api. How can I do to use those validations in Xamarin Form with that validation in every model see this?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.