Problem with a callback function that checks user input

3 ビュー (過去 30 日間)
isdapi
isdapi 2014 年 11 月 30 日
回答済み: isdapi 2014 年 11 月 30 日
I have an edit box and I want that another uicontrol changes its color depending on user input. I have defined a callback function that should control that, but my problem is when the user input a negative value between the valid range because takes "-" as an invalid input.
function check(hObject,~)
inp = get(hObject,'String');
if ~isempty(strfind(inp,','))
warndlg('Invalid input. No commas are allowed','Warning');
set(tex,'BackgroundColor',[.91 .88 .88]);
elseif ~isempty(regexp(inp,'\D','once'))
warndlg('Invalid input. Only numbers are allowed','Warning');
set(tex,'BackgroundColor',[.91 .88 .88]);
elseif str2num(inp)<-360 || str2num(inp)>360
warndlg('RANGE ERROR. Valid values are between -360° and 360°','Warning');
set(tex,'BackgroundColor',[.91 .88 .88]);
elseif str2num(inp)>-360 && str2num(inp)<360
set(tex,'BackgroundColor',[.88 .91 .88])
end
end
So what can I do to solve this?

採用された回答

Geoff Hayes
Geoff Hayes 2014 年 11 月 30 日
isdapi - why not first convert the input to a number and then decide what to do? If the string contains invalid characters, then the conversion will result in an empty matrix. For example, you could do
inp = str2num(get(hObject, 'String'));
if isempty(inp)
% input is invalid
elseif inp < -360 || inp > 360
% input is invalid
else
% input is valid
end
Try the above and see what happens!

その他の回答 (1 件)

isdapi
isdapi 2014 年 11 月 30 日
Thanks!

カテゴリ

Help Center および File ExchangeApp Building についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by