Arh Hokagi
Arh Hokagi

Reputation: 296

Mvvm model validation with INotifyDataErrorInfo

my model implements the INotifyDataErrorInfo interface to validate it's properties, and it works fine, but the probleme is, the property HasErrors is by default false, so when i run my app at the first time and click save (form is empty) the view raise no errors, and the data is saved.

here is a snipet of my viewmodel

public LoggingViewModel()
{
    _loggingCommand = new RelayCommand(checkCredentials, canExecuteLogginForm);
    _logingModel = new LoggingModel();

    // I raise this event in the 'OnErrorsChanged' method in the model,
    // so my ViewModel can subscribe and check the 'HasErrors' property.
    _logingModel.FormIsValid += (o, e) => _loggingCommand.RaiseCanExecuteChanged();
}

private bool canExecuteLogginForm()
{
    return !_logingModel.HasErrors;
}

how do you handle this situation in your app?

for more info i created this github repos.

Upvotes: 0

Views: 1514

Answers (2)

mm8
mm8

Reputation: 169420

As the LogginModel is actually in an invalid state originally you should call the ValidateForm() method in its constructor to actually set it into this state and populate the _errors dictionary in order for the HasErrors property to return true as it should:

public class LoggingModel : PocoBase
{
    public LoggingModel()
    {
        ValidateForm();
    }

    [Display(Name = "Name")]
    [MaxLength(32), MinLength(4)]
    public string UserName
    {
        get { return GetValue<string>(); }
        set { SetValue(value); }
    }

    [Required]
    public string Password
    {
        get { return GetValue<string>(); }
        set { SetValue(value); }
    }
}

Upvotes: 1

robaudas
robaudas

Reputation: 1648

ViewModel logic is correct.
Problem is in your validation logic inside the model which is returning HasErrors = False when HasErrors = true.

Take a look at how you are setting/returning/evaluating HasErrors.
Are you validating the Model on property get?

    public bool HasErrors
    {
        get
        {
            bool hasErrors = false; // Default true here?

            // Validation logic ...

            return hasErrors;
        }
    }

Are you storing the HasError value in a property and setting it somewhere else?

    public LoggingModel()
    {
        HasErrors = true; // Default true here?
    }

    public bool HasErrors { get; set; } // Gets set via validation logic

Just some ideas, like I said if you can show the structure on how you handle INotifyDataErrorInfo validation I can give a better answer.

Upvotes: 0

Related Questions