How to check isNumeric / isNumber in JSTL?

Stefan Michev picture Stefan Michev · Oct 22, 2012 · Viewed 22.6k times · Source

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.

Answer

BalusC picture BalusC · Oct 22, 2012

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.