question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Some questions about adding validation to a TextBox

See original GitHub issue

From the bit of research I’ve done on TextBox validation in Avalonia I’ve gotten this far:

View.axaml:

<TextBox Text="{Binding Email}" Margin="5"/>

ViewModel.cs:

private string email;
public string Email
{
    get
    {
        return email;
    }
    set
    {
        if (string.IsNullOrWhiteSpace(value) || !Regex.IsMatch(value, @"^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$"))
        {
            throw new DataValidationException("Invalid email");
        }

        email = value;
        FirePropertyChanged();
    }
}

image

This works, but I’ve got a couple questions:

  • First, my TextBox does not show a validation error when the window first opens (not until the value of the textbox is changed back). What is the right way to force a validity check when the window first opens?
  • Secondly, I would like to be able to test my validation while debugging but it’s a bit annoying that the VS debugger shows the thrown exception, forcing me to press “Continue” between every character that I type. Is there a way that I can run the program in debug and yet ignore DataValidationExceptions?
  • Finally, is there a way that my viewmodel can check for any current validation issues in the form when the “Ok” button is pressed? (eg in my case above refusing to let the user submit the form if the Email textbox is still showing a validation error)

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Comments:8 (3 by maintainers)

github_iconTop GitHub Comments

2reactions
worldbeatercommented, Jan 20, 2021

@dashenxian you can achieve the described behavior by incorporating WhenAnyValue and a ReactiveCommand probably:

// Each time values of UserName and Password properties change,
// the canExecute observable is signalled and the logic that 
// determines if command execution should be allowed is executed.
var canExecute = this.WhenAnyValue(
    x => x.UserName,
    x => x.Password,
    (userName, password) => 
        !string.IsNullOrEmpty(userName) && 
        !string.IsNullOrEmpty(password));

// The command will be unavailable during execution of the LogOnAsync
// method, or while UserName and Password ViewModel properties are 
// nulls or empty strings. In other words, canExecute supplements 
// the default executability behavior, it doesn't replace it.
var login = ReactiveCommand.CreateFromTask(LogOnAsync, canExecute); // ICommand

Borrowed from https://www.reactiveui.net/docs/handbook/commands/#controlling-executability With ReactiveUI.Validation and their INotifyDataErrorInfo implementation this will look like:

this.ValidationRule(
    x => x.Username,
    name  => !string.IsNullOrWhiteSpace(name),
    "User name shouldn't be null or white space.");

this.ValidationRule(
   x => x.Password,
   pass => !string.IsNullOrWhiteSpace(pass),
   "Password shouldn't be null or white space.");

var canExecute = this.IsValid();
var login = ReactiveCommand.CreateFromTask(LogOnAsync, canExecute); // ICommand
2reactions
worldbeatercommented, Jan 20, 2021

We’ve released a new version of ReactiveUI.Validation recently, with plenty of updates and enhancements. Even complex asynchronous validations are supported now (see our README.md file for more info). Also, we’ve added a sample app targeting Avalonia that shows how to use ReactiveUI.Validation with AvaloniaUI. This should simplify the process of building validations. Remember to install Avalonia.ReactiveUI and add a call to .UseReactiveUI() if you decide to try out ReactiveUI.Validation!

Here is a simple login form validation example. In this example, the Login button stays disabled while the form is invalid:

Read more comments on GitHub >

github_iconTop Results From Across the Web

Validate Textbox Answer Formats
When using Textbox questions, often you will want to validate the data your respondents enter. It makes analyzing, reporting, and then ...
Read more >
Validating Open-Ended Text Fields
You can validate some open-ended question types to require respondents to ... Or, add a new Single Textbox or Multiple Textboxes question to...
Read more >
Textbox Question Type
There are a number of validation options available for Textbox questions. While specific question types exist to collect Email, Percent, ...
Read more >
How to Add Validation to a Text Response Question
Within your form, click on the question you wish to add Validation to; Click on +Options; Select the drop-down beside Validation; Select a ......
Read more >
Response Requirements & Validation
Custom validation is used when you need your respondent to answer a question in a specific way. For example, you may want them...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found