Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop ValidatesOnNotifyDataErrors from being too active

In my application I am using “validatesonnotifydataerrors” along with “DataAnnotations” so that the user is warned if the field they are editing is empty or has the wrong data etc. The problem I have is that when my view is displayed, all the textboxes are showing warnings because they are empty. What I want to do is only show the warning when the user starts entering incorrect data into that field or if they then delete data and the field becomes empty.

Here is the xaml of one of my TextBoxes:

    <TextBox Text="{Binding Path=AttributeName, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=true}" />

Here is the backing property:

    private string _attributeName;
    [StringLength(128)]
    [Required(ErrorMessage = "Field cannot be blank")]
    public string AttributeName
    {
        get { return _attributeName; }
        set
        {
            _attributeName = value;
            IsDirty = true;
            OnPropertyChanged("AttributeName");
        }
    }

Is what I want to do possible with this framework?

like image 466
Retrocoder Avatar asked Sep 17 '26 03:09

Retrocoder


1 Answers

if you want the the textbox to not to show validation straight away, remove the;

[Required(ErrorMessage = "Field cannot be blank")]

And then include a RegularExpression instead, like the following;

[RegularExpression(@"^[a-zA-Z''-'\s]{1,128}$", ErrorMessage = "AttributeName must contain no more then 128 characters and contain no digits.")]
public string AttributeName
{
    get { return _attributeName; }
    set
    {
        _attributeName = value;
        IsDirty = true;
        OnPropertyChanged("AttributeName");
    }
}

Then, within the regular expression, you can add or remove certain aspects so that the textbox doesn't allow numbers, symbols etc.

As you notice, You can add a a range of the string to contain, like so {1,128} (which takes in from 1 letter up to 128, after that it will appear red on the textbox) so in theory, you wouldn't need to include the [StringLength(128)] either.

Take a look at This link for more information about Data Annotations/Attribute validation. And also look at This link also

Hope this helps :).

like image 172
greg Avatar answered Sep 19 '26 10:09

greg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!