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 CenterFile Exchange에서 App Building에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by