Search code examples
javascriptc#blazorblazor-server-sideblazor-webassembly

How can i validate textbox on keypress to allow only alphanumeric characters in blazor server


<InputText @onkeypress="inputfname" id="name" @bind-Value="@model.FirstName">

@code{
    private string _filterRegexPattern = "^[a - zA - Z] *$";

    protected void inputfname(KeyboardEventArgs e)
    {

        if(model.FirstName != _filterReqexPattern)
        {
            fname = "only characters required";
        }
        else
        {
            fname = "";
        }
    }
}

Solution

  • If you want to block the user input I would probably just handle this with an oninput regex. It's going to handle some additional edge cases, like pasting.

    <InputText oninput="this.value = this.value.replace(/[^a-z0-9]/gi, '');" id="name" @bind-Value="@model.FirstName" />
    

    For server side validation you can use the RegularExpressionAttribute on the model.FirstName property.