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

双输入框格式匹配规则实现技术问询

Got it, let's break down how to build this format matching functionality exactly as you described. You need two input fields: one where users define a custom format (using a for letters, n for numbers, and other characters as fixed placeholders), and a second field that has to strictly adhere to that rule.

Here's a practical, real-time implementation using vanilla JavaScript that's easy to integrate and adjust:

Solution Overview

We'll build this in three core steps:

  1. Convert the custom format string into a valid regular expression
  2. Listen for changes on both input fields to trigger validation
  3. Give clear visual feedback to the user about whether their input matches the rule

Full Working Code

<div class="form-group">
  <label for="format-rule">Format Rule (a=letter, n=number, others=fixed):</label>
  <input type="text" id="format-rule" placeholder="e.g., anan-xxx">
</div>
<div class="form-group">
  <label for="input-to-validate">Input to Match:</label>
  <input type="text" id="input-to-validate" placeholder="Enter text matching the rule">
  <span id="validation-feedback"></span>
</div>

<style>
  .form-group { margin: 1rem 0; }
  input { padding: 0.5rem; width: 300px; }
  .valid { border: 2px solid green; }
  .invalid { border: 2px solid red; }
  #validation-feedback { margin-left: 1rem; font-size: 0.9rem; }
</style>

<script>
  const formatInput = document.getElementById('format-rule');
  const validateInput = document.getElementById('input-to-validate');
  const feedback = document.getElementById('validation-feedback');

  // Convert format rule to a regex pattern
  function formatToRegex(format) {
    if (!format) return null;
    // First escape special regex characters (like -, *, ?) to treat them as literals
    let regexPattern = format.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
    // Replace placeholders with their regex equivalents
    regexPattern = regexPattern.replace(/a/g, '[A-Za-z]'); // a = any letter
    regexPattern = regexPattern.replace(/n/g, '[0-9]'); // n = any digit
    // Add start/end anchors to enforce exact match (no extra characters allowed)
    return new RegExp(`^${regexPattern}$`);
  }

  // Validate input against the current format rule
  function validateInputAgainstFormat() {
    const format = formatInput.value.trim();
    const inputValue = validateInput.value.trim();
    
    if (!format) {
      validateInput.classList.remove('valid', 'invalid');
      feedback.textContent = 'Please define a format rule first';
      feedback.style.color = '#666';
      return;
    }

    const regex = formatToRegex(format);
    const isValid = regex.test(inputValue);

    if (isValid) {
      validateInput.classList.add('valid');
      validateInput.classList.remove('invalid');
      feedback.textContent = '✅ Input matches the format!';
      feedback.style.color = 'green';
    } else {
      validateInput.classList.add('invalid');
      validateInput.classList.remove('valid');
      feedback.textContent = '❌ Input does not match the format';
      feedback.style.color = 'red';
    }
  }

  // Trigger validation whenever either input changes
  formatInput.addEventListener('input', validateInputAgainstFormat);
  validateInput.addEventListener('input', validateInputAgainstFormat);
</script>

Key Details Explained

  • Regex Conversion: The formatToRegex function handles the heavy lifting. For example, if your rule is anan-xxx, it converts to the regex ^[A-Za-z][0-9][A-Za-z][0-9]\-xxx$. This is why b1c1-!*> passes (follows the a/n pattern and matches the fixed -xxx part) but 1b1c->!* fails (first character is a number instead of a letter).
  • Real-Time Feedback: The input event listeners mean validation runs instantly as the user types, so they get immediate feedback instead of waiting to submit a form.
  • Literal Placeholder Handling: Special characters like - or * in the format rule are escaped so they're treated as fixed characters, not regex operators.

Customization Options

  • Want to accept uppercase A or N in the format rule? Modify the replace lines to use case-insensitive matching:
    regexPattern = regexPattern.replace(/a/gi, '[A-Za-z]');
    regexPattern = regexPattern.replace(/n/gi, '[0-9]');
    
  • Restrict letters to only uppercase or lowercase? Adjust the regex pattern:
    • Uppercase only: [A-Z]
    • Lowercase only: [a-z]
  • Need optional parts? You could extend the rule syntax (e.g., add ? after a placeholder), but that's an extra feature beyond your original request.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:38:06