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:
- Any number greater than 0. This is to include decimals
- The letter "N" or "n"
- Allow the user to copy/paste (control+c and control+v).
- 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?
2
Answers
You can use more Blazor way to do that and check the string every time the text is changed.
Pasting and arrow keys work as expected.
Reformated info from this blog: https://www.freecodecamp.org/news/javascript-keycode-list-keypress-event-key-codes/ to
Now when you get your
KeyboardEventArgs
callKeyCodes.TryGetValue(eventArgs.Code, out int code);
to get a numeric value like it was in JS.