How to avoid the user insert a number with a wrong value

1 次查看(过去 30 天)
Hi guys, i have a problem, i was making a conversor (Binary, Decimal, Octal, Hexadecimal)
But i have some problems:
What can I do to prevent the user from inserting a wrong amount?
For example: if i put this value on the edit1: 123456 and i choose in the popupmenu 1 as binary then i choose on the popupmenu2 i want to convert it as hexadecimal, obviously it will be an error, because we know 123456 isn't a binary value, maybe for solve this error, we can put a msgbox saying *hey this isn't a binary value*, something like that. But i don't know how to code it.
This is an example:
error.png

回答(1 个)

Walter Roberson
Walter Roberson 2019-9-16
Preventing the user from entering a number that is invalid for the currently selected base is complicated. It requires checking every keystroke as the user types it in, and handling deletions yourself, and (for obscure reasons) keeping track of what the user typed in by yourself.
It is a lot easier to validate the number at the time the conversion is requested.
  • binary: all characters must be members of the set {'0', '1'}
  • octal: all characters must be members of the set {'0', '1', '2', '3', '4', '5', '6', '7'}
  • decimal: all characters must be members of the set {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'}
  • hex: all characters must be members of the set {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'a', 'b', 'c', 'd', 'e', 'f'}
To prevent the user from entering invalid characters, you should study Jan's code at
Notice how he handles one character at a time, and keeps track of what has been typed, and manages deletions "manually" because MATLAB will not track them automatically when you use keypressfcn callbacks.
A more thorough way to handle the situation, at risk of portability, is discussed by Yair at https://undocumentedmatlab.com/blog/editbox-data-input-validation . He shows how to go in at the Java level and hook in validation functions to control what the user can type and what is displayed when the user does type.

类别

Help CenterFile Exchange 中查找有关 Entering Commands 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by