Just 4 fun I’m developing a little RegEx replace tool. The tool is componed by an input string, a search expression (regex search for textbox) and a replace string (replace by textbox). I also implemented a preview Label. The preview is updated on text changed of each on my textboxes.
I would like to add a validation of my regex search expression. If the RegEx string is not valid I would like to add a red icon at the end of my textbox. I know how to do that in old winform but I would like to implement this in MVVM

At this moment my ViewModel is like this:
private string _searchExpression;
public string SearchExpression
{
get { return _searchExpression; }
set
{
if (value != _searchExpression)
{
_searchExpression = value;
OnPropertyChanged("SearchExpression");
OnPropertyChanged("Preview");
}
}
}
private string _replaceExpression;
public string ReplaceExpression
{
get { return _replaceExpression; }
set
{
if (value != _replaceExpression)
{
_replaceExpression = value;
OnPropertyChanged("ReplaceExpression");
OnPropertyChanged("Preview");
}
}
}
public string Preview
{
get
{
if (SelectedFile != null && SearchExpression != null && ReplaceExpression != null)
try
{
return _renamer.Rename(SelectedFile.ToString(), SearchExpression, ReplaceExpression);
}
catch (Exception)
{
return string.Empty;
}
else
return string.Empty;
}
}
First I’ll create a validation method in my business object _renamer. What next? What should I implement in the ViewModel?
- Creating a IsValid property and evaluate it in Preview method or in the setter of SearchExpression?
- Replacing all OnPropertyChanged(“Preview”) by a simple call to a Refresh() method and in this Refresh() method I udpate IsValid property and if it is valid my Preview property?
- Working with converters?
- other solutions?
Also Do you know how to validate a regex. At this moment I try to create it and catch it if it’s wrong. Is it possible to validate it before creating it?
Implementing IDataErrorInfo in your ViewModel will do the thing.
To see the results of validation you will also have to set NotifyOnDataErrors property of the binding to True in xaml you have.