我想知道是否可以通过继承InputBase,最好使用Regex,用Blazor进行屏蔽输入?如果仅使用C#是不可能的,那么JavaScript就可以了。我知道Syncfusion有付费组件,但我更喜欢免费的东西。任何GitHub回购或指导/提示都很好!
我最终(根据Ali Borjian的建议(使用了以下代码,我通过继承InputBase制作了一个组件:
@inject IJSRuntime JSRuntime
@inherits InputBase<string>
<input id="@guid" @attributes="AdditionalAttributes" class="@CssClass" value="@CurrentValue" @oninput="EventCallback.Factory.CreateBinder<string>(this, __value => CurrentValueAsString = __value, CurrentValueAsString)" />
@code {
Guid guid { get; set; }
protected override void OnInitialized()
{
guid = Guid.NewGuid();
}
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender)
{
await JSRuntime.InvokeVoidAsync("mask",guid.ToString(), AdditionalAttributes["data-mask"].ToString());
}
}
protected override bool TryParseValueFromString(string value, out string result, out string validationErrorMessage)
{
result = value;
validationErrorMessage = null;
return true;
}
}
用法:
<EditForm Model="user" OnValidSubmit="Submit">
<div class="form-group">
<label>First Name:</label>
<InputText @bind-Value="user.Name" class="form-control" placeholder="First Name" />
</div>
<div class="form-group">
<label>French Phone no:</label>
<InputMask @bind-Value="user.Telephone" class="form-control" data-mask="00.00.00.00.00" placeholder="Phone No" />
</div>
<button type="submit" class="btn btn-primary">OK</button>
<ValidationSummary />
<DataAnnotationsValidator />
</EditForm>
@code{
private User user = new User();
private void Submit()
{
}
}
在JS中:
window.mask = (id,mask) => {
var customMask = IMask(
document.getElementById(id), {
mask: mask
});
};
我们的类(带有数据注释RegEx(:
public class User
{
[Required]
public string Name { get; set; }
[Required]
[RegularExpression(@"^[0][1-9]([.][0-9][0-9]){4}", ErrorMessage="Incorrect phone number !")]
public string Telephone { get; set; }
}
您可以使用不同的javascript掩码插件,但我建议使用imask(https://github.com/uNmAnNeR/imaskjs)
现在在blazor中执行以下步骤:
1:in_Host.cshtml添加对imask库的引用
< script src="https://unpkg.com/imask">< /script >
2:添加一个javascript文件来处理您的掩码,并添加对_Host.cshtml 的引用
< script src="~/script/customMasks.js">< /script >
3:在customMasks.js中,您可以有不同的掩码,例如电话号码的掩码:
window.masks = () => {
var phoneMask = IMask(
document.getElementById('phone-mask'), {
mask: '+{7}(000)000-00-00'
});
... (other masks)
};
4:现在需要在每个要屏蔽输入的页面中调用window.masks函数,
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender)
{
await JSRuntime.InvokeVoidAsync("mask");
}
}
5:一切都准备好了,现在你可以像这样屏蔽你的输入:
<input type="text" id="phone-mask" />