Textbox - Validation rule
Bonjour,
J'ai une textbox bindée sur un champ TimeSpan. J'utilise un converter pour passer du TimeSpan à un string (hh:mm) et vis versa pour afficher/récupérer la bonne valeur.
J'aimerais pouvoir limiter au maximum le risque d'entrer des valeurs fausses (du genre 12,4, ab:00, etc ...) mais seulement des temps au format hh:mm.
Je voulais utiliser une validation rule avec un regex à l'intérieur, mais je n'arrive pas à corriger efficacement le problème (je peux quand même entrer n'importe quoi)
Est-ce que quelqu'un pourrait m'aider à résoudre ce problème ?
Dans mon xaml, j'appelle ma validation rule comme ceci :
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
|
<TextBox Name="tbxEstimatedTaskTimespan" >
<TextBox.Text>
<Binding Path="EstimatedOPTimespan" UpdateSourceTrigger="PropertyChanged" Mode="TwoWay" >
<Binding.ValidationRules>
<local:HoursValidationRule ValidatesOnTargetUpdated="True" />
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
<TextBox.Style>
<Style TargetType="{x:Type TextBox}">
<Style.Triggers>
<Trigger Property="Validation.HasError" Value="True">
<Setter Property="ToolTip" Value="{Binding RelativeSource={RelativeSource Self}, Path=(Validation.Errors)[0].ErrorContent}"/>
<Setter Property="Background" Value="Red"/>
<Setter Property="Text" Value=""/>
</Trigger>
</Style.Triggers>
</Style>
</TextBox.Style>
</TextBox> |
Ma validation rule ressemble à quelquechose comme ça :
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
{
var s = value as string;
if (string.IsNullOrEmpty(s))
{
return new ValidationResult(false, "Field cannot be blank");
}
//var match = Regex.Match(s, @"^\d{4}:d{2}$");
var match = Regex.Match(s, @"/^([1-9]|1[0-2]):[0-5]");
if (!match.Success)
{
return new ValidationResult(false, "Field must be in hh:mm format");
}
return new ValidationResult(true, null);
} |
Merci d'avance.