WPF验证,正则表达式

时间:2019-05-28 09:56:48

标签: c# wpf validation

我在wpf中验证存在问题。我有一条文字textbox

<TextBox x:Name="Login"  Grid.Column="2" Grid.Row="2">
        <TextBox.Text>
            <Binding  Mode="TwoWay" Path="Email"  UpdateSourceTrigger="PropertyChanged">
                <Binding.ValidationRules>
                    <DataErrorValidationRule />
                </Binding.ValidationRules>
            </Binding>
        </TextBox.Text>
        <TextBox.Style>
                <Setter Property="Validation.ErrorTemplate">
                    <Setter.Value>
                        <ControlTemplate>
                            <DockPanel LastChildFill="True">
                                <TextBlock DockPanel.Dock="Bottom" Foreground="Maroon" FontSize="10pt"
                                           Text="{Binding ElementName=Emael, Path=AdornedElement.(Validation.Errors)[0].ErrorContent}">
                                </TextBlock>
                                <Border BorderBrush="DarkRed" BorderThickness="1">
                                    <AdornedElementPlaceholder Name="Emael" />
                                </Border>
                            </DockPanel>
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>
            </Style>
        </TextBox.Style>
    </TextBox>

和属性

 public string Error => throw new NotImplementedException();

    public string this[string columnName]
    {
        get
        {
            string error = String.Empty;

            switch (columnName)
            {
                case "Email": 
                    if (Email == null || Email == string.Empty)
                    {
                        error = "Field login must be required";
                    }
                    break;
            }
            return error;
        }
    }

我不知道如何在这里使用正则表达式,在后端我使用dataAnnotation

[Required(ErrorMessage = "This field should be filled in")]
[RegularExpression(@"\w+(@)[a-zA-z]+(\.)[a-zA-z]+", ErrorMessage = ("Use the right email format"))]

如何以表格形式编写相同的逻辑(客户端验证)。编写自己的验证类并以某种方式与属性连接可能会更好?有什么更好的办法?

1 个答案:

答案 0 :(得分:0)

您可以将注释复制到视图模型中,并实现一种为您验证注释的方法:

[Required(ErrorMessage = "This field should be filled in")]
[RegularExpression(@"\w+(@)[a-zA-z]+(\.)[a-zA-z]+", ErrorMessage = ("Use the right email format"))]
public string Email { get; set; }

public string Error => throw new NotImplementedException();

public string this[string columnName]
{
    get
    {
        string error = String.Empty;

        switch (columnName)
        {
            case "Email":
                return ValidateModelProperty(Email, columnName);
        }
        return error;
    }
}

private string ValidateModelProperty(object value, string propertyName)
{
    ICollection<ValidationResult> validationResults = new List<ValidationResult>();
    ValidationContext validationContext =
        new ValidationContext(this, null, null) { MemberName = propertyName };
    if (!Validator.TryValidateProperty(value, validationContext, validationResults))
        foreach (ValidationResult validationResult in validationResults)
            return validationResult.ErrorMessage;
    return null;
}

有关更多信息,请参阅this博客文章。