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

Angular 1.6 文本框实时限制指定数值格式输入需求咨询

Real-Time Input Restriction for Angular 1.6

Got it, let's figure out how to restrict your input field to only accept the exact formats you listed—no post-input validation errors, just immediate blocking of invalid characters. Here's a solid approach using a custom directive, which is the go-to way for DOM input control in Angular 1.x:

Step 1: Create a Custom Directive

We'll build a directive that listens to both keystrokes and paste events to enforce your allowed formats (10, +10, -10, +10.00, -10.00, +10.00%, -10.00%). It'll block invalid keys as they're pressed and clean up any invalid pasted content.

angular.module('yourAppName').directive('restrictedNumberInput', function() {
  return {
    restrict: 'A',
    link: function(scope, element) {
      // Regex for valid intermediate input (allows partial entries like "+" or "10.")
      const allowedPartialPattern = /^[-+]?\d*(\.\d{0,4})?%?$/;
      // Regex for valid final input (strict match for your required formats)
      const allowedFinalPattern = /^[-+]?\d+(\.\d{1,4})?%?$|^\d+%?$/;

      // Handle keydown to block invalid key presses
      element.on('keydown', function(e) {
        const key = e.key;
        // Allow essential control keys (backspace, delete, arrows, tab)
        const controlKeys = ['Backspace', 'Delete', 'ArrowLeft', 'ArrowRight', 'Tab'];
        if (controlKeys.includes(key)) return;

        // Build the potential new value with the pressed key
        const currentVal = element.val();
        const caretPos = element[0].selectionStart;
        const potentialVal = currentVal.slice(0, caretPos) + key + currentVal.slice(caretPos);

        // Block the key if the potential value is invalid
        if (!allowedPartialPattern.test(potentialVal)) {
          e.preventDefault();
        }
      });

      // Handle paste/drop events to clean up invalid content
      element.on('input', function() {
        let inputVal = element.val();
        
        // First, strip out any completely invalid characters
        inputVal = inputVal.replace(/[^-+.\d%]/g, '');

        // Ensure only one decimal point exists
        if (inputVal.split('.').length > 2) {
          const parts = inputVal.split('.');
          inputVal = parts[0] + '.' + parts.slice(1).join('');
        }

        // Limit decimal places to 4
        const dotIndex = inputVal.indexOf('.');
        if (dotIndex !== -1) {
          const decimalPart = inputVal.slice(dotIndex + 1);
          if (decimalPart.length > 4) {
            inputVal = inputVal.slice(0, dotIndex + 5);
          }
        }

        // Ensure % only appears once, at the end
        if (inputVal.includes('%')) {
          inputVal = inputVal.replace(/%/g, '') + '%';
        }

        // If the final value doesn't match the strict pattern, trim invalid trailing content
        if (!allowedFinalPattern.test(inputVal)) {
          // Fallback: remove the last character if it breaks the pattern
          inputVal = inputVal.slice(0, -1);
        }

        element.val(inputVal);
      });
    }
  };
});

Step 2: Use the Directive in Your HTML

Simply add the directive attribute to your input field:

<input type="text" restricted-number-input placeholder="Enter value (e.g. +10.00%)">

Key Notes

  • Intermediate vs Final Patterns: The allowedPartialPattern lets users type valid partial entries (like starting with + before entering numbers), while allowedFinalPattern enforces the strict end format.
  • Control Keys: We let essential navigation keys work so users can edit normally.
  • Paste Handling: The input event catches pasted content and cleans it up to fit your rules, so even if someone tries to paste invalid text, it gets corrected immediately.
  • Flexibility: Adjust the decimal place limit (currently 4) or regex patterns if your requirements change slightly.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 08:36:32