JSF驗證浮點數值範圍


<f:validateDoubleRange>標籤用於驗證一個浮點(float/double)值的範圍。

以下程式碼顯示如何使用<f:validateDoubleRange>標記

<f:validateDoubleRange minimum="1000.50" maximum="10000.50" />

標籤屬性

屬性 說明
minimum 在可選範圍內最小長度值
maximum 在可選範圍內最大長度值

JSF驗證整數範圍範例

開啟 NetBeans IDE 建立一個Web工程:ValidateDoubleValueRange,其目錄結構如下所示 -

JSF驗證浮點數值範圍

建立以下檔案程式碼,檔案:index.xhtml 的程式碼內容如下所示 -

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"   
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:f="http://java.sun.com/jsf/core">
    <h:body>
        <h:form>
            <h:panelGrid columns="3">
                Enter a double value: 
                <h:inputText id="salary" value="#{user.salary}" 
                             size="10" required="true"
                             label="Salary" >
                    <f:validateDoubleRange minimum="10.11" maximum="10000.99" />
                </h:inputText>
                <h:message for="salary" style="color:red" />
            </h:panelGrid>
            <h:commandButton value="Submit" action="result" />
        </h:form>
    </h:body>
</html>

檔案:result.xhtml 的程式碼內容如下所示 -

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"   
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:f="http://java.sun.com/jsf/core"
      xmlns:c="http://java.sun.com/jsp/jstl/core"
      >
    <h:body>
        Salary :  <h:outputText value="#{user.salary}" />
    </h:body>
</html>

檔案:User.java 的程式碼內容如下所示 -

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.yiibai;

/**
 *
 * @author Maxsu
 */
import java.io.Serializable;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

@ManagedBean(name = "user")
@SessionScoped
public class User implements Serializable {

    double salary;

    public double getSalary() {
        return salary;
    }

    public void setSalary(double salary) {
        this.salary = salary;
    }

}

右鍵執行工程:ValidateDoubleValueRange,如果沒有任何錯誤,開啟瀏覽器存取:

http://localhost:8084/ValidateDoubleValueRange/

應該會看到以下結果 -

簡單寫入一些資訊(大於10),然後提交 -