Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Blazor input mask

Tags:

c#

blazor

I’d like to know if it’s possible to make a masked input with Blazor by inheriting InputBase, and preferably using Regex? If not possible with C# only then JavaScript is fine. I know Syncfusion has a paid component, but I’d prefer free stuff. Any GitHub repo or guidance/hint is just fine!

like image 429
raphadesa Avatar asked May 01 '20 11:05

raphadesa


2 Answers

I ended up (baesed on Ali Borjian's advice) using the following code, I made a component by inheriting from 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;
    }
}

Usage:

<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()
    {
    }
}

And in JS:

window.mask = (id,mask) => {
        var customMask = IMask(
            document.getElementById(id), {
            mask: mask
        });
    };

And our class (with a Data Annotations 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; }

    }
like image 173
raphadesa Avatar answered Oct 18 '22 10:10

raphadesa


You can use different javascript mask plugins, but I suggest imask (https://github.com/uNmAnNeR/imaskjs)

Now in blazor follow these steps :
1: In _Host.cshtml add a reference to the imask library

< script src="https://unpkg.com/imask">< /script >


2: Add a javascript file to handle your masks, and add its reference to _Host.cshtml

< script src="~/script/customMasks.js">< /script >


3: In customMasks.js you can have different masks, e.g a mask for phone number :

    window.masks = () => {

    var phoneMask = IMask(
        document.getElementById('phone-mask'), {
        mask: '+{7}(000)000-00-00'
    });

    ... (other masks)

   };


4: Now you need to call the window.masks function in each page that you want to mask the inputs,

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


5: everything is ready, now you can mask your inputs like this :

 <input type="text" id="phone-mask" />
like image 21
Ali Borjian Avatar answered Oct 18 '22 10:10

Ali Borjian