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

1 vue (au cours des 30 derniers jours)
Jhon Rackham
Jhon Rackham le 15 Sep 2019
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

Réponses (1)

Walter Roberson
Walter Roberson le 16 Sep 2019
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.

Catégories

En savoir plus sur Entering Commands dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by