How can I limit the TextBox control to only allow the values 0 and 1?
Thanks. And I have one more question: How can I disable put text from clipboard in my textbox control?
By default, HTML 5 input field has attribute type=”number” that is used to get input in numeric format. Now forcing input field type=”text” to accept numeric values only by using Javascript or jQuery. You can also set type=”tel” attribute in the input field that will popup numeric keyboard on mobile devices.
You can use an <input type="number" /> . This will only allow numbers to be entered into othe input box.
To give a limit to the input field, use the min and max attributes, which is to specify a maximum and minimum value for an input field respectively. To limit the number of characters, use the maxlength attribute.
The <input type="number"> defines a field for entering a number. Use the following attributes to specify restrictions: max - specifies the maximum value allowed. min - specifies the minimum value allowed.
By using the event KeyPress
private void NumericOnlyKeyBox_KeyPress(object sender, KeyPressEventArgs e)
{
var validKeys = new[] { Keys.Back, Keys.D0, Keys.D1 };
e.Handled = !validKeys.Contains((Keys)e.KeyChar);
}
Setting e.Handled
to true / false indicates if the character should be accepted to the box or not.
You can read more about KeyPressEventArgs on MSDN.
Note
Keys.Delete should cover Keys.Delete, Keys.Backspace and other "Back" buttons.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With