防止将非数字输入到 Blazor 的输入中

时间:2021-01-08 14:22:31

标签: blazor blazor-server-side blazor-webassembly

在 Blazor 应用程序中,我有一个 <input type="text" />,我正在尝试做一些事情,以便无法在其中输入非数字字符。

这是我到目前为止所做的,而且似乎运行良好:

<input type="text" @bind="InputContent" @bind:event="oninput" />

@code {
    string inputContent;
    string InputContent
    {
        get => inputContent;
        set => inputContent = StripNonDigits(value);
    }

    string StripNonDigits(string str)
    {
        return new String(str.Where(c => char.IsDigit(c)).ToArray());
    }
}

现在,我想知道:

  • 还有哪些其他方法可以实现这一目标:“特别是在 Blazor 中,监视并可能修改用户输入的内容。”例如,这可以在不使用 @bind 的情况下实现吗?
  • 我的做法是否存在潜在问题?或者这是一个最佳解决方案?

在 JS 中,要执行相同的操作,您将监听 oninput 事件,如果输入的字符不是数字,则执行 event.preventDefault()。据我所知,您不能在 Blazor 中完全做到这一点,对吗?

2 个答案:

答案 0 :(得分:0)

也许验证的东西对你有帮助? 通常它在提交时触发,但这里描述了如何使用继承自 InputText 的新输入组件在输入时触发:link

<块引用>
> @* Inherits from the original InputText component *@
@inherits InputText
@* Bind the oninput event *@
<input @attributes="AdditionalAttributes"
       class="@CssClass"
       value="@CurrentValue"
       @oninput="EventCallback.Factory.CreateBinder<string>(this, __value => CurrentValueAsString = __value, CurrentValueAsString)" />

然后你可以使用正则表达式来禁止数字:

@using System.ComponentModel.DataAnnotations;

<EditForm Model="example">
    <DataAnnotationsValidator />
    <ValidationSummary />
    <InputTextOnInput @bind-Value="example.Name"></InputTextOnInput>
    <button type="submit">Submit</button>
</EditForm>


@code {

public class ExampleModel
{
    [Required]
    [RegularExpression(@"^[a-zA-Z''-'\s]{1,40}$",
     ErrorMessage = "Characters are not allowed.")]
    public string Name { get; set; }
}

public ExampleModel example = new ExampleModel();

}

答案 1 :(得分:-1)

不可靠的解决方案:

这就是@enet 提出的解决方案实际上非常不可靠、有缺陷、效率低下和幼稚的原因。 + 为什么他声称我的解决方案有问题实际上是错误的。

更新:他删除了他的回答。

首先,他的解决方案不优雅的原因:

原因一:无法通过快捷键(Ctrl/CMD + V)防止复制粘贴

无评论:

enter image description here

原因 2:无法通过上下文菜单阻止复制粘贴(右键单击 => 粘贴)

无评论:

enter image description here

原因3:无法防止文本拖放

无评论:

enter image description here

原因 4:仅适用于英文数字

无评论:

enter image description here

原因 5:文本中间不可编辑(重要!)

无评论:

enter image description here

注意:您可以在这个小提琴中看到所有这些行为:https://blazorfiddle.com/s/xfik4hnq

原因 6:使用 RegEx

RegEx 速度慢、效率低,而且通常难以阅读和解析。因此,应尽可能避免。

enter image description here

原因 7:更复杂,更不优雅

说真的,没有评论,很明显。

原因 8:需要更多行代码

仅考虑@code 部分,@enet 提出的这个解决方案大约有 23 行代码,而我的大约有 12 行。(都考虑到一行上的花括号等)

注意:同样重要的是要记住,如果这个解决方案几乎和我最初提出的一样健壮(我将解释一下),它必须解决每一个刚刚演示的问题,为了做到这一点,它必须变得比现在复杂得多,而且还需要更多的代码行。

最佳解决方案:

这就是为什么我最初在原始问题中提出的解决方案是最优化和最优雅的解决方案;

解决所有上述问题,而且更少的代码行+代码这更容易理解、更短、更好、更简单。

与此同时,另一方提出的唯一支持另一种解决方案和反对我的解决方案的论点是,我的解决方案导致不允许的字符出现几分之一秒,然后消失。然而,在我的任何测试中都没有观察到这一点。

以下是演示这一点的 GIF:

每当我按下键盘上的某个键时,您都可以在控制台上看到类似“按下的键:a”之类的消息,但同时,您会看到该字符没有出现在全部在输入中:

enter image description here

相关问题