0

I'm using ValidationRules in my xaml forms like this

      <TextBox Name="email">
            <TextBox.Text>
                  <Binding Path="email" UpdateSourceTrigger="PropertyChanged">
                        <Binding.ValidationRules>
                              <local:NotEmptyString  ValidationStep="RawProposedValue" />
                        </Binding.ValidationRules>
                  </Binding>
            </TextBox.Text>
      </TextBox>

In code, before my transaction begins i check for errors like this

email.GetBindingExpression(TextBox.TextProperty).UpdateSource();

if (Validation.GetHasError(item))
      return false;

I have classes that inherit ValidationRule for every validation i need, and this works fine.

But now, i need to call a post method and that method returns me an JSON error when the email already exists, I want to show that error as a validation error. is there a way to set the error to the TextBox?

Rodo D
  • 13
  • 3

1 Answers1

0

If you want to stick to this quite unflexible binding validation, then the simplest solution would be to use Binding.ValidatesOnException:

<TextBox Name="email">
  <TextBox.Text>
    <Binding Path="email" 
             UpdateSourceTrigger="PropertyChanged"
             ValidatesOnException="True">
      <Binding.ValidationRules>
        <local:NotEmptyString  ValidationStep="RawProposedValue" />
      </Binding.ValidationRules>
    </Binding>
  </TextBox.Text>
</TextBox>

Then validate your JSON response:

class ViewModel
{
  public string Email { get; set; }

  private ValidateJsonResponse(Json jsonObject)
  {
    if (!JsonIsValid(jsonObject))
    {
      throw new ArgumentException("Email already exists.");
    }
  }
}

But since exceptions can have some impact on the performance, you generally should avoid them. You can argue, if failed input validation is a good reason to throw an exception. I doubt it is.

Alternatively implement a second ValidationRule and trigger the binding to execute it. You must find a way to access the JSON response to check whether it is valid or not. Since the ValidationRule is instantiated in the XAML and can't have a DependencyProperty to allow binding, this could be slightly complicated. That's why binding validation is not very flexible. The ValidationRule instance of the binding is quite isolated from the rest of the code e.g., the view model.

The recommended pattern is to have your view model implement he INotifyDataErrorInfo interface. See this post for an example or links regarding the implementation: How to add validation to view model properties or how to implement INotifyDataErrorInfo

BionicCode
  • 1
  • 4
  • 28
  • 44