我想知道是否可以通过继承InputBase并最好使用Regex来使用Blazor进行屏蔽输入?如果仅使用C#无法实现,那么JavaScript就可以了。我知道Syncfusion具有付费功能,但是我更喜欢免费的东西。任何GitHub存储库或指南/提示都很好!
答案 0 :(得分:4)
我最终使用了以下代码(根据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
});
};
还有我们的课程(带有数据注释正则表达式):
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; }
}
答案 1 :(得分:1)
您可以使用其他javascript掩码插件,但我建议使用imask(https://github.com/uNmAnNeR/imaskjs)
现在闪闪发光,请按照以下步骤操作:
1:在_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" />