Skip to content

Instantly share code, notes, and snippets.

@dfmmalaw
Last active July 10, 2018 17:49
Show Gist options
  • Select an option

  • Save dfmmalaw/9dc639472663a427768bd5242046757e to your computer and use it in GitHub Desktop.

Select an option

Save dfmmalaw/9dc639472663a427768bd5242046757e to your computer and use it in GitHub Desktop.
I added validation to an email address form field. Instead of doing the validation on the CSLA object we decided to put the validation in the viewmodel. This decision was made due to it being lower risk than involving the CSLS properties in the valid
<StackPanel Grid.Row="3" Grid.Column="1" Margin="3,0,5,0" Orientation="Vertical" HorizontalAlignment="Stretch" VerticalAlignment="Center">
<TextBox HorizontalAlignment="Left" VerticalAlignment="Center" Text="{Binding EmailAddress,Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Width="150" Margin="0, 5"/>
<TextBlock Text="Email address is not valid" Foreground="Red" Visibility="{Binding DataContext.IsEmailAddressInvalidVisible,Mode=OneWay, FallbackValue='Collapsed', RelativeSource={RelativeSource FindAncestor,AncestorType={x:Type UserControl}}}"/>
</StackPanel>
private bool _isEmailAddressInvalid;
public bool IsEmailAddressInvalid
{
get { return _isEmailAddressInvalid; }
set
{
_isEmailAddressInvalid = value;
RaisePropertyChanged("IsEmailAddressInvalid");
RaisePropertyChanged("IsEmailAddressInvalidVisible");
}
}
public Visibility IsEmailAddressInvalidVisible
{
get { return _isEmailAddressInvalid ? Visibility.Visible : Visibility.Collapsed; }
}
public RelayCommand<object> SaveCommand
{
get
{
if (_saveCommand == null)
{
_saveCommand = new RelayCommand<object>(
(param) =>
{
NewCustomer = NewCustomer.Save();
args.PersonId = NewCustomer.PersonId;
//Messenger.Default.Send<CloseViewEvent>(new CloseViewEvent(this, this.InstanceKey));
PublishEvent<CloseViewEvent, Guid>(new CloseViewEvent(this, this.InstanceKey), this.InstanceKey);
},
(param) =>
{
return NewCustomer != null && NewCustomer.IsSavable && CustomerPhone != null && CustomerPhone.IsValid && IsEmailAddressValid(NewCustomer.EmailAddress);
});
}
return _saveCommand;
}
}
private bool IsEmailAddressValid(string emailAddress)
{
emailAddress = emailAddress ?? String.Empty;
var isValid = System.Text.RegularExpressions.Regex.IsMatch(emailAddress, @"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$");
// empty email address allowed since it is optional
if (emailAddress == String.Empty)
{
isValid = true;
}
IsEmailAddressInvalid = !isValid;
return isValid;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment