How to check isNumeric / isNumber in JSTL?
Asked Answered
H

3

7

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.

Hartmann answered 22/10, 2012 at 9:21 Comment(0)
D
10

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.

Diffusivity answered 22/10, 2012 at 21:34 Comment(0)
F
6

If you really insist on

(without extending any java classes and additional JSP functions)

then you could use the following hack.

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<c:set var="x" value="8" />
<c:catch var="isNumber">
   <c:set var="x" value="${x * 1}" />
</c:catch>
<c:if test="${isNumber == null}">
    ... do something ...
</c:if>
<c:if test="${isNumber != null}">
      ... do not do anything...
</c:if>
Far answered 22/10, 2012 at 15:42 Comment(1)
I didn't know about <c:catch>, it's not a perfectly neat solution, but it does the job. One could argue that is is abusing exceptions, but if it is actually an "exception" to receive a number and you expect a number, this is actually not too bad. In many cases the code could also be simpler, more like <c:set var="n" value="0"/> <c:catch><c:set var="n" value="${input * 1}"/></c:catch>Filth
D
2

You can create a custom function as explained in the following tutorials:

  1. Creating Custom functions in JSP using JSTL
  2. How to create a custom Function for JSTL
  3. Another tutorial

Steps to create a function from the above links:

  1. Create a .tld file under /WEB-INF:

    <?xml version="1.0" encoding="UTF-8"?>
    <taglib version="2.1" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-jsptaglibrary_2_1.xsd">
         <tlib-version>1.0</tlib-version>
         <short-name>functionalTlds</short-name>
         <uri>http://www.rasabihari.com/functionalTlds</uri>
         <function>
             <name>isNumeric</name>
             <function-class>com.expressions.Functions</function-class>
             <function-signature>boolean isNumeric(java.lang.String)</function-signature>
         </function>
    </taglib>
    
  2. Create a class with the method (the logic of the method is taken from here, it uses Regular Expression)

    package com.expressions;
    
    /**
      *
      * @author rasabihari
      */
    public class Functions {
        public static boolean isNumeric(String number) {  
            boolean isValid = false;  
            /*
            Explaination: 
            [-+]?: Can have an optional - or + sign at the beginning. 
            [0-9]*: Can have any numbers of digits between 0 and 9 
            \\.? : the digits may have an optional decimal point. 
            [0-9]+$: The string must have a digit at the end. 
            If you want to consider x. as a valid number change  
            the expression as follows. (but I treat this as an invalid number.). 
            String expression = "[-+]?[0-9]*\\.?[0-9\\.]+$"; 
            */  
    
            String expression = "[-+]?[0-9]*\\.?[0-9]+$";  
            CharSequence inputStr = number;  
            Pattern pattern = Pattern.compile(expression);  
            Matcher matcher = pattern.matcher(inputStr);  
    
            if(matcher.matches()){  
                isValid = true;  
            }
    
            return isValid;  
        }
    }  
    
  3. And then use it in the JSP as:

    <%@page contentType="text/html" pageEncoding="UTF-8"%>
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">
    <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
    <%@taglib uri="http://www.rasabihari.com/functionalTlds" prefix="ftld" %>
    <html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <c:if test="${ftld:isNumeric('123')}">
           <!-- ... do something ...
               This block will run
            -->
        </c:if>
    </body>
    </html>
    
Decahedron answered 22/10, 2012 at 15:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.