Forum Xamarin Cross Platform with Xamarin

How should i validate a View Model and display error messages using Fluent Validation?

RamprasadKRamprasadK USMember ✭✭

How should i validate a View Model and display error messages using Fluent Validation?
Here is my code... And I really didn't know how to display error messages in Content page, Kindly help me on this...

Thanks in advance....

Validator and View Model:

public class AreaValidator : AbstractValidator
{
public AreaValidator()
{
RuleFor(Area => Area.AreaName).NotEmpty().WithMessage("Missing Area Name");
RuleFor(Area => Area.City).NotEmpty().WithMessage("Missing City");
// RuleFor(Area => Area.State).NotEqual(0).When(Area => Area.HasDiscount);
RuleFor(Area => Area.State).NotEmpty().WithMessage("Missing State");
RuleFor(Area => Area.Phone).NotEmpty().WithMessage("Please enter a valid phone number").MaximumLength(10).WithMessage("Do not exceed 10 digits");
}
}

public class AreaViewModel : BaseVM
{
private readonly IValidator _validator;
// public ObservableRangeCollection arearangecoll { get; set; }
public AreaViewModel Vmodel { get; set; }
string name;
public string AreaName
{
get { return name; }
set
{
if (SetProperty(ref name, value))
{
// this.ValidateProperty(value, nameof(AreaName));
}
}
}
public string State { get; set; }
public string City { get; set; }
public string Phone { get; set; }
public byte[] Image { get; set; }

    public AreaViewModel()
    {
        _validator = new AreaValidator();
        VmvalidateCommand = new Command(async () => await VMValidateasync(Vmodel));
    }
    public void IsValid()
    {
        this._validator.Validate(this);
    }
    public Command VmvalidateCommand { get; }

    public async Task VMValidateasync(AreaViewModel model)
    {
        if (IsBusy)
            return;
        try
        {
            IsBusy = true;
            await Task.Delay(2000);
            // IsValid();
            ValidationResult results = _validator.Validate(model);
            bool validationSucceeded = results.IsValid;
            IList<ValidationFailure> failures = results.Errors;
            IsBusy = false;
        }
        catch (Exception ex)
        {

        }
    }

}


        <Label Text="Name"></Label>
        <Entry Text="{Binding AreaName}">
        </Entry>
        <Label Text="State"></Label>
        <Entry Text="{Binding State}"></Entry>
        <Label Text="City"></Label>
        <Entry Text="{Binding City}"></Entry>
        <Label Text="Phone"></Label>
        <Entry Text="{Binding Phone}"></Entry>

        <StackLayout Orientation="Vertical" Spacing="5">
            <Button Text="Save" Clicked="Button_Clicked" Margin="10,10,10,0" HorizontalOptions="Center"/>
            <ActivityIndicator IsRunning="{Binding IsBusy}" IsVisible="{Binding IsBusy}" Color="Red"></ActivityIndicator>
        </StackLayout>

Best Answers

Answers

  • RamprasadKRamprasadK USMember ✭✭
    edited August 2017

    Hi @smhasan @AlessandroCaliaro @Sumit_Sharma

    Kindly help me on this...
    Thanks in advance...

  • RamprasadKRamprasadK USMember ✭✭

    Hi @AlessandroCaliaro
    Thanks for the reply....
    Then How should you validate your view model?

  • AlessandroCaliaroAlessandroCaliaro ITMember ✭✭✭✭✭

    never used fluentvalidation...

  • smhasansmhasan KWMember ✭✭

    Dear @RamprasadK Sorry, I also never used fluentvalidation

  • RamprasadKRamprasadK USMember ✭✭

    @smhasan Then How can you Validate your Fields In Xamarin Cross Platform PCL Project

    If there is vs solution for that,Kindly post the file or link.

    Thanks in advance

  • smhasansmhasan KWMember ✭✭

    @RamprasadK , we are using Behaviors and Triggers to approach validation on fields in Xamarin Cross Plate Form PCL,
    The below code is C# to validate max length in Entry

    //MaxLengthValidator Class

         public class MaxLengthValidator : Behavior<Entry>
            {
                public static readonly BindableProperty MaxLengthProperty = BindableProperty.Create("MaxLength", typeof(int), typeof(MaxLengthValidator), 0);
                static readonly BindablePropertyKey IsValidPropertyKey = BindableProperty.CreateReadOnly("IsValid", typeof(bool), typeof(MaxLengthValidator), false);
    
                public static readonly BindableProperty IsValidProperty = IsValidPropertyKey.BindableProperty;
    
                public int MaxLength
                {
                    get { return (int)GetValue(MaxLengthProperty); }
                    set { SetValue(MaxLengthProperty, value); }
                }
    
                protected override void OnAttachedTo(Entry bindable)
                {
                    bindable.TextChanged += bindable_TextChanged;
                }
                public bool IsValid
                {
                    get { return (bool)base.GetValue(IsValidProperty); }
                    private set { base.SetValue(IsValidPropertyKey, value); }
                }
                private void bindable_TextChanged(object sender, TextChangedEventArgs e)
                {
                    //if (MaxLength != null && MaxLength.HasValue)
                    if (e.NewTextValue.Length > 0 && e.NewTextValue.Length > MaxLength)
                        ((Entry)sender).Text = e.NewTextValue.Substring (0, MaxLength);
                    if (e.NewTextValue.Length < MaxLength)
                        IsValid = false;
                    else
                        IsValid = true;
                    ((Entry)sender).TextColor = IsValid ? Color.Default : Color.Red;
    
                }
    
                protected override void OnDetachingFrom(Entry bindable)
                {
                    bindable.TextChanged -= bindable_TextChanged;
    
                }
            }  
    

    // In code add to your Entry like txtMobile

    txtMobile.Behaviors.Add(new MaxLengthValidator { MaxLength = 8 });

    Please let me know if you need in Xamal also, but I like to work in C# only not in Xamal

Sign In or Register to comment.