如何强制接受Maui Blazor中的HTML输入只能是数字?

huangapple go评论85阅读模式
英文:

How to force to accept only numbers html input for Maui Blazor?

问题

我想防止输入除整数以外的任何内容到 <input> 中。

我正在使用 Maui Blazor 和 MudBlazor。对于常规的 Blazor 在电脑上可以工作,但在手机上不能。

&lt;MudNumericField
    @bind-Value=&quot;value&quot;
    Label=&quot;标准&quot;
    Variant=&quot;Variant.Text&quot; 
    Min=&quot;0&quot; 
    Max=&quot;10&quot;
    Pattern=&quot;[0-9]&quot; /&gt;

@code {
    int value = 0;
}
英文:

I would like to prevent to type anything else only integers for <input>.

I am using Maui Blazor with MudBlazor.
For regular Blazor on computer this works, but on phone does not.

&lt;MudNumericField
    @bind-Value=&quot;value&quot;
    Label=&quot;Standard&quot;
    Variant=&quot;Variant.Text&quot; 
    Min=&quot;0&quot; 
    Max=&quot;10&quot;
    Pattern=&quot;[0-9]&quot; /&gt;

@code {
    int value = 0;
}

答案1

得分: 0

在普通的输入标签中,您只需这样做:

<input type="number" inputmode="numeric"/>
英文:

In the normal input tag you can just do this

&lt;input type=&quot;number&quot; inputmode=&quot;numeric&quot;/&gt; 

答案2

得分: 0

在最后,我用以下方式解决了这个问题:

Razor.cs:

private int? _integerValue;

[Inject]
public IJSRuntime JSRuntime { get; set; } = default!;

protected override async Task OnAfterRenderAsync(bool firstRender)
{
    if (firstRender)
    {
        await JSRuntime.InvokeVoidAsync("mask");
    }
}

CustomMasks.js:

window.mask = () => {
    const integerMask = {
        mask: Number,
        min: 0,
    };

    var elements = document.querySelectorAll(".positive-integer input");
    elements.forEach(element => {
        IMask(element, integerMask);
    });
};

Razor:

<MudNumericField @bind-Value="_integerValue" Class="positive-integer"/>
英文:

In the end i solved with these:

Razor.cs

private int? _integerValue;

[Inject]
public IJSRuntime JSRuntime { get; set; } = default!;
protected override async Task OnAfterRenderAsync(bool firstRender)
{
    if (firstRender)
    {
        await JSRuntime.InvokeVoidAsync(&quot;mask&quot;);
    }
}

CustomMasks.js

window.mask = () =&gt; {
    const integerMask = {
        mask: Number,
        min: 0,
    };

    var elements = document.querySelectorAll(&quot;.positive-integer input&quot;);
    elements.forEach(element =&gt; {
        IMask(element, integerMask);
    });
};

Razor:

&lt;MudNumericField @bind-Value=&quot;_integerValue&quot; Class=&quot;positive-integer&quot;/&gt;

huangapple
  • 本文由 发表于 2023年8月4日 02:02:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/76830588.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定