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

Bootstrap 4.1:使用自定义JavaScript验证JSON RPC表单输入

Hey there! Let's get that JSON validation working for your Bootstrap 4.1 RPC test page. I've put together a complete implementation that ties into your existing JSON.parse() approach, with proper Bootstrap styling and custom error feedback. Here's how to do it:

Step 1: Update Your HTML Form Structure

First, adjust your form to use Bootstrap's built-in form validation classes. This ensures error messages look consistent with Bootstrap's design:

<form id="rpcDebugForm" novalidate>
  <div class="form-group mb-4">
    <label for="rpcParams" class="font-weight-bold">JSON RPC Parameters</label>
    <textarea 
      class="form-control" 
      id="rpcParams" 
      rows="6" 
      placeholder="Enter your JSON object here (e.g., {&quot;id&quot;: 1, &quot;method&quot;: &quot;getStatus&quot;})"
      required
    ></textarea>
    <!-- Custom error feedback area -->
    <div class="invalid-feedback" id="jsonValidationError">
      Please enter valid JSON format.
    </div>
  </div>
  <button type="submit" class="btn btn-primary">Send RPC Request</button>
</form>
Step 2: Implement the Validation Logic

Next, add JavaScript to handle both real-time input validation and form submission checks. This uses your existing JSON.parse() idea but wraps it in error handling to generate meaningful feedback:

// Grab DOM elements
const rpcForm = document.getElementById('rpcDebugForm');
const paramsTextarea = document.getElementById('rpcParams');
const errorElement = document.getElementById('jsonValidationError');

// Core JSON validation function
function validateJsonInput(inputText) {
  try {
    // Attempt to parse the input
    JSON.parse(inputText);
    // If no error, return true for valid
    return { valid: true };
  } catch (parseError) {
    // Capture the specific error message to show the user
    return {
      valid: false,
      message: `Invalid JSON: ${parseError.message}`
    };
  }
}

// Real-time validation as user types (improves UX)
paramsTextarea.addEventListener('input', () => {
  const inputValue = paramsTextarea.value.trim();
  
  if (!inputValue) {
    // Reset to default required message if empty
    errorElement.textContent = 'JSON parameters cannot be empty.';
    paramsTextarea.classList.remove('is-valid');
    paramsTextarea.classList.add('is-invalid');
    return;
  }

  const validationResult = validateJsonInput(inputValue);
  if (validationResult.valid) {
    paramsTextarea.classList.remove('is-invalid');
    paramsTextarea.classList.add('is-valid');
  } else {
    paramsTextarea.classList.remove('is-valid');
    paramsTextarea.classList.add('is-invalid');
    errorElement.textContent = validationResult.message;
  }
});

// Form submission validation
rpcForm.addEventListener('submit', (e) => {
  e.preventDefault(); // Stop default form submit
  
  const inputValue = paramsTextarea.value.trim();
  
  // First check if input is empty
  if (!inputValue) {
    errorElement.textContent = 'JSON parameters cannot be empty.';
    paramsTextarea.classList.add('is-invalid');
    return;
  }

  // Run JSON validation
  const validationResult = validateJsonInput(inputValue);
  if (!validationResult.valid) {
    paramsTextarea.classList.add('is-invalid');
    errorElement.textContent = validationResult.message;
    return;
  }

  // If we get here, JSON is valid! Proceed with RPC call
  const parsedParams = JSON.parse(inputValue);
  console.log('Valid RPC parameters:', parsedParams);
  
  // Add your RPC request logic here (e.g., fetch, XMLHttpRequest)
  // Example:
  // fetch('/your-rpc-endpoint', {
  //   method: 'POST',
  //   headers: { 'Content-Type': 'application/json' },
  //   body: JSON.stringify(parsedParams)
  // })
  // .then(response => response.json())
  // .then(data => console.log('RPC Response:', data));
});
Key Details to Note
  • Bootstrap Integration: We use Bootstrap's is-invalid/is-valid classes to style the textarea and invalid-feedback to display errors. This keeps your page consistent with Bootstrap's design system.
  • Meaningful Error Messages: Instead of a generic error, we capture the actual message from JSON.parse() (like "Unexpected token '}' at position 10") to help users debug their input faster.
  • Real-Time Feedback: The input event listener checks validity as the user types, so they get immediate feedback instead of waiting until submission.
  • Fallback Validation: The form submit handler re-runs validation to prevent any edge cases where real-time validation might be bypassed.

If you need to add additional checks (like verifying the JSON matches your RPC's required structure), you can extend the validation function to inspect the parsed JSON object before proceeding.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:04:49