I'm creating a simple custom currency component in Blazor. I inherit from InputBase<string> and implement bool TryParseValueFromString(string value, out TValue result, out string validationErrorMessage)
The problem is that i want to return value when the TryParseValueFromString is not successful.
Parent component
<div class="form-group mb-3">
<label for="MyInputTextArea">Input currency</label>
<InputCurrency @bind-Value=FormData.SomeStringCurrency id="MyInputTextArea" class="form-control"/>
<ValidationMessage For="() => FormData.SomeStringCurrency"></ValidationMessage>
</div>
Custom component
@using System.Globalization
@inherits InputBase<string>
<input type="string" @attributes=AdditionalAttributes class=@CssClass @bind=CurrentValueAsString />
@code{
private CultureInfo _culture = CultureInfo.CreateSpecificCulture("de");
protected override string FormatValueAsString(string value)
{
if (string.IsNullOrWhiteSpace(value))
{
return string.Empty;
}
if (Decimal.TryParse(value, NumberStyles.Currency, _culture, out decimal result))
{
return Convert.ToDecimal(value).ToString("N", _culture);
}
else
{
return value;
}
}
protected override bool TryParseValueFromString(string value, out string result, out string validationErrorMessage)
{
try
{
var decimalValue = ReturnDecimalIfSuccessFul(value);
result = decimalValue.ToString();
validationErrorMessage = null;
return true;
}
catch
{
validationErrorMessage = "Not a valid currency value.";
result = value; // here i am assigning the value but it's not returned
return false;
}
}
private decimal? ReturnDecimalIfSuccessFul(string value)
{
if (string.IsNullOrWhiteSpace(value))
{
return null;
}
var result = Decimal.Parse(value, NumberStyles.Currency, _culture);
return result;
}
When the value is not successfully parsed then is not showed to the user. Only the last successfully value is showed, but I expect to always have the value user put in input...