Vishal Vishal - 1 month ago 3
C# Question

How to check if Model is valid or has errors while using IDataErrorInfo

This question might be very much simple, but I can't find a way to do it, so I asked it.

I used IDataErrorInfo in my model to validate it as follows:

public class Group : INotifyPropertyChanged, IDataErrorInfo
{
//Fileds & Properties

public string Error
{
get { return String.Empty; }
}

public string this[string columnName]
{
get
{

if (columnName == "GroupName")
{
bool _IsDuplicateGroupName;

using (MunimPlusContext context = new MunimPlusContext())
{
_IsDuplicateGroupName = context.GroupSet.Any(x => x.GroupName.ToLower() == GroupName.ToLower());
}

if (String.IsNullOrWhiteSpace(GroupName))
{
return "Group Name cannot be Empty.";
}
else if (_IsDuplicateGroupName)
{
return "Duplicate Group Name. Please choose a unique Group Name.";
}
}

if (columnName == "ParentId")
{
if (ParentId == null)
{
return "Please select Under Group under which " + (GroupName == null ? "this" : GroupName) + " Group will appear.";
}
else if (ParentId <= 0)
{
return "Please select a valid GroupName from the list.";
}
}

if (columnName == "NatureOfGroupId")
{
Group _PrimaryGroup;
using (MunimPlusContext context = new MunimPlusContext())
{
_PrimaryGroup = context.GroupSet.Where(x => x.GroupName == "Primary").FirstOrDefault();
}

if (_PrimaryGroup.GroupId == ParentId)
{
if (NatureOfGroupId == null)
{
return "Please select the Nature of Group.";
}
else if (NatureOfGroupId <= 0)
{
return "Please select a valid Nature of Group from the list.";
}
}
}

return String.Empty;
}
}
}


Now, in my XAML:

<Grid.Resources>
<DataTemplate DataType="{x:Type ValidationError}">
<TextBlock FontStyle="Italic" Foreground="Red" HorizontalAlignment="Right" Text="{Binding ErrorContent}" Margin="4,0,4,4" />
</DataTemplate>
</Grid.Resources>

<TextBlock Grid.Row="3" Grid.Column="1" Text="Name" />
<TextBlock Grid.Row="3" Grid.Column="1" Text=":" />
<TextBox Grid.Row="3" Grid.Column="2" x:Name="txtGroupName" Text="{Binding GroupName, ValidatesOnDataErrors=True, UpdateSourceTrigger=PropertyChanged}"/>
<ContentPresenter Grid.Row="4" Grid.Column="2" Content="{Binding ElementName=txtGroupName, Path=(Validation.Errors).CurrentItem}" />

<TextBlock Grid.Row="5" Grid.Column="1" Text="Alias" />
<TextBlock Grid.Row="5" Grid.Column="1" Text=":" />
<TextBox Grid.Row="5" Grid.Column="2" x:Name="txtAlias" Text="{Binding Alias, ValidatesOnDataErrors=True}"/>
<ContentPresenter Grid.Row="6" Grid.Column="2" Content="{Binding ElementName=txtAlias, Path=(Validation.Errors).CurrentItem}" />

<TextBlock Grid.Row="7" Grid.Column="1" Text="Under" />
<TextBlock Grid.Row="7" Grid.Column="1" Text=":" />
<ComboBox Grid.Row="7" Grid.Column="2" x:Name="cmbParentGroup"
ItemsSource="{DynamicResource Items}" SelectedValue="{Binding ParentId, ValidatesOnDataErrors=True, UpdateSourceTrigger=PropertyChanged}"
SelectedValuePath="Group.GroupId" Grid.IsSharedSizeScope="True" TextSearch.TextPath="Group.GroupName" LostFocus="cmbParentGroup_LostFocus"/>
<ContentPresenter Grid.Row="8" Grid.Column="2" Content="{Binding ElementName=cmbParentGroup, Path=(Validation.Errors).CurrentItem}" />

<TextBlock Grid.Row="9" Grid.Column="1" Text="Nature Of Group" />
<TextBlock Grid.Row="9" Grid.Column="1" Text=":" />
<ComboBox Grid.Row="9" Grid.Column="2" x:Name="cmbNatureOfGroup"
ItemsSource="{Binding DataContext.NaturesOfGroup, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type core:UserControlViewBase}}}"
DisplayMemberPath="Nature" SelectedValue="{Binding NatureOfGroupId, ValidatesOnDataErrors=True, UpdateSourceTrigger=PropertyChanged}"
SelectedValuePath="NatureOfGroupId" LostFocus="cmbNatureOfGroup_LostFocus"/>
<ContentPresenter Grid.Row="10" Grid.Column="2" Content="{Binding ElementName=cmbNatureOfGroup, Path=(Validation.Errors).CurrentItem}" />

<StackPanel Grid.Row="11" Grid.Column="2" Orientation="Horizontal" HorizontalAlignment="Right">
<Button Content="Save" Style="{StaticResource SaveButtonWithText}"
Command="{Binding DataContext.SaveCommand, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type core:UserControlViewBase}}}"/>
<Button Content="Cancel" Style="{StaticResource CancelButtonWithText}"
Command="{Binding DataContext.CancelCommand, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type core:UserControlViewBase}}}"/>
</StackPanel>


Now, when I save my Data to the database, I want to check if my Model is valid or not. How can I do so?

Answer

At last, got my answer from this post.

Here is my code for IDataErrorInfo Implementation:

public string Error
{
    get { return null; }
}

public string this[string propertyName]
{
    get { return GetValidationError(propertyName); }
}

private static readonly string[] ValidatedProperties = { "GroupName", "ParentId", "NatureOfGroupId" };

public bool IsValid
{
    get
    {
        foreach (string property in ValidatedProperties)
        {
            if (GetValidationError(property) != null)
            {
                return false;
            }
        }
        return true;
    }
}

private string GetValidationError(string propertyName)
{
    string error = null;

    switch (propertyName)
    {
        case "GroupName":

            bool _IsDuplicateGroupName;

            using (MunimPlusContext context = new MunimPlusContext())
            {
                _IsDuplicateGroupName = context.GroupSet.Any(x => x.GroupName.ToLower() == GroupName.ToLower());
            }

            if (String.IsNullOrWhiteSpace(GroupName))
            {
                error = "Group Name cannot be Empty.";
            }
            else if (_IsDuplicateGroupName)
            {
                error = "Duplicate Group Name. Please choose a unique Group Name.";
            }

            break;

        case "ParentId":

            if (ParentId == null)
            {
                error = "Please select Under Group under which " + (GroupName == null ? "this" : GroupName) + " Group will appear.";
            }
            else if (ParentId <= 0)
            {
                error = "Please select a valid GroupName from the list.";
            }

            break;

        case "NatureOfGroupId":

            Group _PrimaryGroup;
            using (MunimPlusContext context = new MunimPlusContext())
            {
                _PrimaryGroup = context.GroupSet.Where(x => x.GroupName == "Primary").FirstOrDefault();
            }

            if (_PrimaryGroup.GroupId == ParentId)
            {
                if (NatureOfGroupId == null)
                {
                    error = "Please select the Nature of Group.";
                }
                else if (NatureOfGroupId <= 0)
                {
                    error = "Please select a valid Nature of Group from the list.";
                }
            }

            break;

    }

    return error;

}

Here is how I check that if all the properties are valid for an object called CurrentGroup?

if (CurrentGroup.IsValid)
{
       //save data to the database.......
}