locked
Validation with DataAnnotations RRS feed

  • Question

  • Hi,

    I have a application with MVVM and I need a range rule validation.
    I have this code in viewmodel:

    [Range(1, 100, ErrorMessage = "El número de fotos debe pertenecer al rango: 1 .. 100")]
    public int NumFotos
    {
    get { return _numFotos; }
    set
    {
    if ((this._numFotos != value))
    {
    Validator.ValidateProperty(value, new ValidationContext(this, null, null)
    {
    MemberName = "NumFotos",
    });
    }
    _numFotos = value;
    RaisePropertyChanged("NumFotos");
    }
    }

    In XAML view I have the Binding:
    TextBox Text="{Binding NumFotos, Mode=TwoWay,
    ValidatesOnExceptions=True,
    NotifyOnValidationError=True}" MinWidth="25"

    If I introduce some value in the textBox, the validation raise and works fine, but I don't put any value and I click on summit button without modify the default value of the textbox(0) the validation don't works and the value are incorrect for my Range rule. Any idea?

    Thanks.
    Sunday, April 25, 2010 5:16 PM

Answers

  •  I guess it comes from the default value.

    The default value for an int is 0 so I guess the value of your textbox is 0.

    If you submit your fields the set of your property is not called (except if you have some code which validate through your controls and validate the values). If you want to, you will have to call the UpdateSource method of the BindingExpression (with textBox.GetBinding(...).UpdateSource()).

    But even here I think it will not be ok because you'll not enter because of the if ((this._numFotos != value)).

    A solution will be to set the value of your property to 1 in the constructor.

    Sunday, April 25, 2010 9:36 PM