function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
ForceComForceCom 

Pattern Matching

Hi, 

 

I am trying to check if an integer field has a string value , if yes display an error. 

 

if(totalunit != '' && totalunit != null && !Pattern.matches('\\d*', totalunit)){
ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 'WARNING: Total Unit Quanitity Requested Only Accepts Number.'));
return null;
}

 

I am facing an error saying " Comparison arguments must be compatible types: Integer, String".

 

I would appreciate any help or pointers ...

 

Thank you 

 

jungleeejungleee

You have to cast the totalunit to string before you do a matching..

 

You could do something like this

 

if(totalunit != '' && totalunit != null && !Pattern.matches('\\d*', string.valueOf(totalunit))){
	ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 'WARNING: Total Unit Quanitity Requested Only Accepts Number.'));
	return null;
}

//Suppose the totalUnit contains decimal then the above fails to check that. To check decimals you could do:

if(totalunit != '' && totalunit != null && !Pattern.matches('\\d+(\\.\\d*)?', string.valueOf(totalunit))){
	ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 'WARNING: Total Unit Quanitity Requested Only Accepts Number.'));
	return null;
}

 Hope it helps!!