Skip to content

Commit

Permalink
changes to publish package name validation
Browse files Browse the repository at this point in the history
- moved small fixes to publish package name validation to this branch
  • Loading branch information
dnenov committed Nov 29, 2023
1 parent 64058c6 commit 7cc915a
Showing 1 changed file with 33 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using System.Globalization;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Navigation;

Expand All @@ -11,7 +12,7 @@ public class PackageNameLengthValidationRule : ValidationRule
{
public override ValidationResult Validate(object value, CultureInfo cultureInfo)
{
if (value is string name && name.TrimEnd().Length > 2)
if (IsValidName((string)value))
{
// Validation succeeded
return ValidationResult.ValidResult;
Expand All @@ -20,6 +21,11 @@ public override ValidationResult Validate(object value, CultureInfo cultureInfo)
// Validation failed
return new ValidationResult(false, Wpf.Properties.Resources.NameNeedMoreCharacters);
}
public static bool IsValidName(string value)
{
return (value is string name && name.TrimEnd().Length > 2);
}

}


Expand Down Expand Up @@ -136,11 +142,36 @@ private void textBoxInput_PreviewKeyDown(object sender, System.Windows.Input.Key
{
var textBox = sender as TextBox;
if (textBox == null) return;
if (e.Key == Key.System) return;

int caretIndex = textBox.CaretIndex; // Store the caret index

// Prevents text starting with a space
if (e.Key == System.Windows.Input.Key.Space && string.IsNullOrWhiteSpace(textBox.Text))
{
e.Handled = true;
e.Handled = true;
return;
}

if (string.IsNullOrEmpty(textBox.Text)) { return; }

// In case we are using the Backspace to remove characters, the validation error will stop the Name property from being updated
if (textBox.Name.Equals("packageNameInput") && e.Key == Key.Back && !PackageNameLengthValidationRule.IsValidName(textBox.Text.Substring(0, textBox.Text.Length - 1)))
{
e.Handled = true;

if (!string.IsNullOrEmpty(PublishPackageViewModel.Name))
{
// Manually remove the last character from the Name property, as the validation error will not update the Name property
PublishPackageViewModel.Name = PublishPackageViewModel.Name.Substring(0, PublishPackageViewModel.Name.Length - 1);

// Trigger re-validation explicitly
var expression = textBox.GetBindingExpression(TextBox.TextProperty);
expression?.UpdateSource();

textBox.CaretIndex = caretIndex - 1 >= 0 ? caretIndex - 1 : 0;
return;
}
}
}
}
Expand Down

0 comments on commit 7cc915a

Please sign in to comment.