You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在JSP中验证表格行内动态生成的文本框?

Dynamic Textbox Validation (Min/Max/Normal Range)

Problem Overview

You’ve built a table with dynamic textboxes where each row includes three inputs:

  • min[<%=i%>]: Defines the minimum value for the row
  • max[<%=i%>]: Defines the maximum value for the row
  • normal[<%=i%>]: Value that must fall between the min and max

The required validations per row are:

  1. The max[i] value can’t be smaller than min[i]
  2. The normal[i] value must lie within the range set by min[i] and max[i]

Client-Side Validation (JavaScript)

Add real-time validation to give users immediate feedback. You can trigger this on form submission or as the user types.

Example Code

function validateRows() {
    let isFormValid = true;
    const tableRows = document.querySelectorAll('#dynamic-table tr'); // Replace with your table ID
    
    tableRows.forEach((row, index) => {
        // Get input elements for the current row
        const minInput = row.querySelector(`input[name="min[${index}]"]`);
        const maxInput = row.querySelector(`input[name="max[${index}]"]`);
        const normalInput = row.querySelector(`input[name="normal[${index}]"]`);
        
        if (!minInput || !maxInput || !normalInput) return;
        
        // Parse values to numbers
        const minVal = parseFloat(minInput.value);
        const maxVal = parseFloat(maxInput.value);
        const normalVal = parseFloat(normalInput.value);
        
        // Reset error states
        [minInput, maxInput, normalInput].forEach(input => input.classList.remove('invalid'));
        
        // Check for valid numeric inputs
        if (isNaN(minVal) || isNaN(maxVal) || isNaN(normalVal)) {
            alert(`Row ${index + 1}: Please enter valid numbers in all fields`);
            isFormValid = false;
            return;
        }
        
        // Validate max >= min
        if (maxVal < minVal) {
            alert(`Row ${index + 1}: Max value can't be less than Min value`);
            maxInput.classList.add('invalid');
            isFormValid = false;
        }
        
        // Validate normal is within range
        if (normalVal < minVal || normalVal > maxVal) {
            alert(`Row ${index + 1}: Normal value must be between Min and Max`);
            normalInput.classList.add('invalid');
            isFormValid = false;
        }
    });
    
    return isFormValid;
}

// Attach to form submission
document.getElementById('your-form-id').addEventListener('submit', (e) => {
    if (!validateRows()) {
        e.preventDefault(); // Stop form from submitting if invalid
    }
});

Quick Tips:

  • Add a CSS class .invalid to highlight faulty inputs (e.g., border: 1px solid #dc3545;)
  • For real-time checks, attach the validation function to the input event of each textbox instead of form submit.

Server-Side Validation (Java JDBC)

Client-side validation can be bypassed, so always validate on the server before processing data. Here’s how to integrate it with your existing JDBC code:

Example Code

// Retrieve form parameters (adjust if using a framework like Spring)
Map<String, String[]> formParams = request.getParameterMap();
List<String> validationErrors = new ArrayList<>();

// Get number of rows (track this with a hidden input in your form)
int rowCount = Integer.parseInt(request.getParameter("rowCount"));

for (int i = 0; i < rowCount; i++) {
    String minStr = request.getParameter("min[" + i + "]");
    String maxStr = request.getParameter("max[" + i + "]");
    String normalStr = request.getParameter("normal[" + i + "]");
    
    try {
        double minVal = Double.parseDouble(minStr);
        double maxVal = Double.parseDouble(maxStr);
        double normalVal = Double.parseDouble(normalStr);
        
        // Check max >= min
        if (maxVal < minVal) {
            validationErrors.add("Row " + (i+1) + ": Max value cannot be less than Min value");
        }
        
        // Check normal is in range
        if (normalVal < minVal || normalVal > maxVal) {
            validationErrors.add("Row " + (i+1) + ": Normal value must lie between Min and Max");
        }
    } catch (NumberFormatException e) {
        validationErrors.add("Row " + (i+1) + ": All fields require valid numeric values");
    }
}

// Handle errors if any
if (!validationErrors.isEmpty()) {
    request.setAttribute("errors", validationErrors);
    request.getRequestDispatcher("your-form-page.jsp").forward(request, response);
    return;
}

// Proceed with your JDBC logic if validation passes
Connection con = null;
try {
    con = connection.createConnection();
    System.out.println("Printing connection object " + con);
    
    // Use PreparedStatement instead of Statement to prevent SQL injection
    String sql = "INSERT INTO itemfi (min_val, max_val, normal_val) VALUES (?, ?, ?)";
    PreparedStatement pstmt = con.prepareStatement(sql);
    
    // Loop through rows again to insert valid data
    for (int i = 0; i < rowCount; i++) {
        double minVal = Double.parseDouble(request.getParameter("min[" + i + "]"));
        double maxVal = Double.parseDouble(request.getParameter("max[" + i + "]"));
        double normalVal = Double.parseDouble(request.getParameter("normal[" + i + "]"));
        
        pstmt.setDouble(1, minVal);
        pstmt.setDouble(2, maxVal);
        pstmt.setDouble(3, normalVal);
        pstmt.addBatch();
    }
    
    pstmt.executeBatch();
} catch (SQLException e) {
    e.printStackTrace();
    // Handle database errors gracefully
} finally {
    // Clean up resources
    if (con != null) {
        try {
            con.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

Key Notes:

  • Always use PreparedStatement instead of raw Statement to avoid SQL injection risks
  • Pass validation errors back to the form page to display them to the user
  • Adjust the SQL query to match your actual database schema

内容的提问来源于stack exchange,提问作者Harsha Dave

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 03:32:02