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:
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., {"id": 1, "method": "getStatus"})" 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>
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)); });
- Bootstrap Integration: We use Bootstrap's
is-invalid/is-validclasses to style the textarea andinvalid-feedbackto 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
inputevent 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

