Blazor - How do you prevent non-numeric characters in a Textbox (InputText)?

Viewed 5427

I have an InputText in blazor and I want to prevent non-numeric characters, what is the basic razor and c# code to do that? here is how I need it to work, a user enters a character and it refuses the entry all together AND displays a validation message that says only Numbers are allowed. So far I've tried datanotations range attribute using regex but that does not refuse nonnumeric characters.

6 Answers

It's actualy a html/javascript thing. Adding

onkeypress="return (event.charCode !=8 && event.charCode ==0 || (event.charCode >= 48 && event.charCode <= 57))"

to your html input element will prevent user from typing in non-numerics. If you need to display a validation message, i would rather use something like

@oninput="async () => await isInputNumeric()"

in this element then create funtion

private async Task isInputNumeric() { // call javascript to check the what is inside you input element (what is the last character) and act accordingly -> show message and delete the non-numeric character OR carry on if input is numeric }

You would have to use javascript since blazor does not yet have the c# way of accessing the html elements.

dinozaver answered your question well, but I want to add some (I think very important) advice: you aren't obligated to use Blazor's custom controls, which mainly handle validation.

If you want a numeric input, I recommend just using one:

<input type="number" @bind="MyImportantNumber" />

@code 
{
     int MyImportantNumber { get; set; }
}

You can get more info Here. HTML number inputs allow you to set min/max values, the step amount of the spinner control and so on. Also, using an html number control on a mobile device will popup a numerical keypad, which users might find convenient.

If you are into a EditForm context you can use the blazor component InputNumber for edit Int32, Int64, Int16, Single, Double, Decimal. According to Blazor Docs it's rendered like:

<input type="number"/>

Example of use:

<EditForm Model="myObject">
    <InputNumber @bind-Value="myObject.mydouble" />
    <ValidationMessage For="()=> myObject.mydouble"/>
</EditForm>

@code {
    private MyObject myObject = new MyObject();

    class MyObject {
        public double mydouble { get; set; }
    }
} 

Thanks to ValidationMessage component, if user tries to input non-numeric characters a message is displayed. The type of binding variable can be inferred by the compiler, or you can explicity indicate like:

<InputNumber TValue="double" @bind-Value="myObject.mydouble" />

Can't comment the other's answer but it works perfect!

Add to the Script section in Host.cshtml:

$(document).on("keypress",".numbers", function (e) {
                return (e.charCode != 8 && e.charCode == 0 || (e.charCode >= 48 && e.charCode <= 57));
            });
$(document).on("paste", ".numbers", function (e) {
            e.preventDefault();
            let paste = (e.originalEvent.clipboardData || window.clipboardData).getData('text');
            this.value = paste.replace(/\D/g, '');
            this.dispatchEvent(new Event('change'));
            });

Your input must contain class="numbers":

<input type="text" class="numbers" @bind-value="@anyValue"/>

you can add jquery as helper.

<input type="text" @bind="Model" class="NumberOnly" />

and put this code on MainLayout.razor

<script>  
$(document).on("keypress", ".NumberOnly", function(e){
    return (e.charCode !=8 && e.charCode ==0 || (e.charCode >= 48 && e.charCode <= 57));
});
</script>
Related