Search code examples
asp.netrazorblazorrazor-2

Blazor key press event and KeyCodes


I am creating a control in a Razor Control Library. I am trying to only allow a few keys presses to be allowed in a text box. They are:

  1. Any number greater than 0. This is to include decimals
  2. The letter "N" or "n"
  3. Allow the user to copy/paste (control+c and control+v).
  4. Allow arrows and tab key

I can easily do this in Javascript, by using the Keycode. In JS, I would do this:

keyPress: function (e) {
        var datatype = e.currentTarget.getAttribute("data-type");
        settings.valueChange.call();
        //add 110, 190 for decimal          
        if ($.inArray(e.keyCode, [46, 8, 9, 27, 13]) !== -1 ||
            // Allow: Ctrl+A,Ctrl+C,Ctrl+V, Command+A
            ((e.keyCode == 65 || e.keyCode == 86 || e.keyCode == 67) && (e.ctrlKey === true || e.metaKey === true)) ||
            // Allow: home, end, left, right, down, up
            (e.keyCode >= 35 && e.keyCode <= 40)) {
            // let it happen, don't do anything
            if (e.keyCode == 86) {
                //PASTE                
            }
            return;
        }
        if (e.keyCode === 78) {
            e.preventDefault();               
            //its an N, do some stuff
        } else if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
            e.preventDefault();
        }
    }

But, how would I do this in Blazor/Razor? The KeyboardEventArgs does not seem to provide the KeyCode. I could use jsInterop to call my JS function, but, again, KeyboardEventArgs does not provide the JS KeyCode. How can I either accomplish this in Blazor or get the numeric KeyCode, so I can pass this to my JS function?


Solution

  • You can use more Blazor way to do that and check the string every time the text is changed.

    @using System.Text.RegularExpressions;
    <input @bind-value="@InputValue" @bind-value:event="oninput"/>
    <h4>@InputValue </h4>
    
    @code {
        private string _inputVal = "";
        public string InputValue {
            get => _inputVal;
            set { 
            if((double.TryParse(value,out double d) && d>0)//is the number like 1.23
              || value.ToLower()=="n" || value=="" )//or is N,n or empty str
                _inputVal = value;
            }
            }
    }
    

    Pasting and arrow keys work as expected.