I suspect one of your main issues is that you have your input type set as "number" instead of "text". Although, based on your naming convention, it looks like you're wanting it to input numbers...but I don't see why there'd be a need to prevent an "e" or "-" entered if that was the case, so I'm assuming you're wanting to input text?
Either way, here are some adjustments that should generally answer your question and have it functioning, then you can tweak it from there.
It looks like you must have a CustomInputBase.cs file, so adjust it like this:
public class CustomInputBase : InputBase<string>
{
[Parameter] public string Id { get; set; }
[Parameter] public string Label { get; set; }
[Parameter] public string PlaceHolder { get; set; }
[Parameter] public string AriaLabel { get; set; }
[Parameter] public bool ShowDefaultOption { get; set; } = true;
[Parameter] public Expression<Func<string>> ValidationFor { get; set; }
protected override bool TryParseValueFromString(string value, out string result, out string validationErrorMessage)
{
result = value;
validationErrorMessage = null;
return true;
}
}
CustomInputNumber.razor (I also added a way to detect when backspace was entered)
@inherits CustomInputBase
@inject IJSRuntime JSRuntime
<div class="form-control-wrapper">
@if (!string.IsNullOrWhiteSpace(Label))
{
<label class="form-control-label" for="@Id">@Label</label>
}
<input type="text" class="form-control txtNumero" id="@Id" @bind="@CurrentValue" placeholder="@PlaceHolder" aria-label="@AriaLabel" @ref="inputElement"
@onkeydown="KeyBoardEventHandler" @onkeydown:preventDefault />
<div class="form-control-validation">
<ValidationMessage For="@ValidationFor" />
</div>
</div>
<p>@KeyPressed</p>
<p>@EventInfo</p>
@code {
private ElementReference inputElement;
string KeyPressed = "";
string EventInfo = "";
void KeyBoardEventHandler(KeyboardEventArgs args)
{
KeyPressed = "Key Pressed is " + args.Key;
EventInfo = "Event Type " + args.Type;
string[] invalidStringsArray = { "e", "-" };
if (args.Key == "Backspace")
{
CurrentValue = CurrentValue.Remove(CurrentValue.Length - 1);
}
else
{
if (invalidStringsArray.Contains(args.Key))
{
args.Key = string.Empty;
}
CurrentValue += args.Key;
}
}
}
Then enter it into a component like this. Now it will not enter and "e" or "-".
<EditForm Model="model">
<CustomInputNumber @bind-Value="model.CurrentValue" ValidationFor="(() => model.CurrentValue)" Label="My Label" />
</EditForm>
@code {
SomeModel model = new SomeModel();
public class SomeModel
{
public string SomeString { get; set; }
public string CurrentValue { get; set; }
}
}
Posted 3 years ago
by selliott
Edited 3 years ago