Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check isNumeric / isNumber in JSTL?

How to do this simple check in JSTL (without extending any Java classes and additional JSP functions). I need it like this:

<c:if test="${fn:isNumeric()}">
    // do something
</c:if>

Thanks in advance.

like image 981
Stefan Michev Avatar asked Oct 22 '12 09:10

Stefan Michev


1 Answers

If your environment supports the new EL 2.2 feature of invoking non-getter methods on EL objects (which is available in all Servlet 3.0 compatible containers, such as Tomcat 7, Glassfish 3, etc), then you could just use the String#matches() method directly in EL.

<c:set var="numberAsString">${someExpressionToTestForNumber}</c:set>
<c:if test="${numberAsString.matches('[0-9]+')}">
    It's a number!
</c:if>

(I'll leave the minus - and the thousands and fraction separators , and . outside consideration as possible characters which may appear in a technically valid number)

Note that the <c:set> with the expression in its body implicitly converts any type to String using String#valueOf(). Otherwise the matches() call in <c:if> would fail for non-String types.

like image 197
BalusC Avatar answered Oct 19 '22 16:10

BalusC