User123
User123

Reputation: 599

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

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.

Upvotes: 9

Views: 18306

Answers (8)

Sith2021
Sith2021

Reputation: 3736

Pure C#

<input type="text" class="input-group"
       @bind="text"
       @onkeydown=OnKeyDown
       @onkeydown:preventDefault=@preventDefault
       @bind:event="oninput" />

@code {
    string text = string.Empty;

    bool preventDefault = false;
 
    void OnKeyDown(KeyboardEventArgs e)
    {
        preventDefault = IsNumericLetter(e.Key, text) == false;
    }

    static bool IsNumericLetter(string letter, string text)
    {
        if(letter == "Backspace" || letter == "ArrowLeft" || letter == "ArrowRight" || letter == "Delete" || letter == "Enter") {
            return true;
        }
        // validate key pressed
        char keyChar = letter.ToCharArray()[0];

        if(char.IsDigit(keyChar)) {
            return true;
        }
        if(keyChar == '-' && text.Contains('-') == false && text.Length == 0 /* only first char */) {
            return true;
        }
        if(keyChar == '.' && text.Contains('.') == false) {
            return true;
        }
        return false;
    }
}

Upvotes: 2

Olgierd Kuczyński
Olgierd Kuczyński

Reputation: 41

I know it's been a while, but I solved this problem using only html + cs. You don't need any js. If anyone still needs to enter data using only letters, check it out, it's worth using this simple solution.

Explanation:

Since the OnKeyDown method executes before the OnInput method, PreventDefault will be specified there to display or not display a character other than letters or spaces. I used Regular Expressions to check the correctness of the entered character.

Solution:

You need to take care of 4 things:

  • binding Value to your input
  • handle the @oninput method
  • handle the @onkeydown method
  • handle the @onkeydown:preventDefault property

The html section should looks like this:

<input @bind=@Value
       @onkeydown=OnKeyDown 
       @onkeydown:preventDefault=@PreventDefault
       @oninput="@((x) => { OnInput((string)x.Value); })" />

In the @code section, use such properties and methods:

private string Value;
private bool PreventDefault = false;
private Regex rgx = new Regex("[^a-zA-Z ']")
private void OnInput(string value) => Value = value;
private void OnKeyDown(KeyboardEventArgs e) => PreventDefault = rgx.Replace(e.Key, "") == ""; 

I hope it will be useful.

Upvotes: 4

Ivan  Pavlovsky
Ivan Pavlovsky

Reputation: 1

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"/>

Upvotes: 0

bportela
bportela

Reputation: 119

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" />

Upvotes: 3

hesolar
hesolar

Reputation: 709

I think you can solve it with a Html tag, just use : <input type="number ...> You can check here the documentation. https://developer.mozilla.org/es/docs/Web/HTML/Element/input/number

Upvotes: 0

H. Ashari
H. Ashari

Reputation: 1

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>

Upvotes: -2

Bennyboy1973
Bennyboy1973

Reputation: 4256

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.

Upvotes: 6

dinozaver
dinozaver

Reputation: 137

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.

Upvotes: 10

Related Questions