函数 jquery.alphanumeric

Function with jquery.alphanumeric

我想在 html 模式中实现 jquery.alphanumeric,所以我使用 here

的 jquery 插件

这是我的代码

<input type="text" char-allow="$#*" class="alpha">
<input type="text" char-allow="+-" class="numeric">
<input type="text" char-allow="&" class="alphanumeric">

<script>
    function setAlphaNumeric(){
        $(".numeric").each(function(){
            var a = $(this).attr("char-allow"); $(this).numeric({allow:a});
        });
        $(".alpha").each(function(){
            var a = $(this).attr("char-allow"); $(this).alpha({allow:a});
        });
        $(".alphanumeric").each(function(){
            var a = $(this).attr("char-allow"); $(this).alphanumeric({allow:a});
        });
    }

$(function(){

setAlphaNumeric();

});
</script>

还有比那个代码更短和最好的吗?

仅供参考,有了 jQuery 和对 RegEx 的一些简单使用,您真的不需要插件。非常简单。

Update! Here's a quick breakdown of first example.

  • $(document).on:在这里,我只是利用 DOM 的 document 变量通过 jQuery live 功能分配事件。这是确保 DOM 完成加载后加载的元素(动态元素)仍将遵守给定事件任务的便捷方法。
  • .on('keydown', '.alpha':前2个参数分别是我们的event and our selector。我选择 keydown 事件是因为我们可以通过返回 boolean 值来控制是否显示字符。如果返回 false,则不会将任何字符打印到 UI。
  • var a = e.key;: jQuery 事件足以将请求的字符转换为字符串。在这里,我只是将该字符串分配给一个变量进行检查!
  • if (a.length == 1):原因很简单,如果String大于1或者小于1,那么它就不是一个字符。您可以通过在 Event 方法中使用类似 console.debug(a); 的内容,然后在输入输入时观察您的控制台来自己查看。例如,Backspace 键将具有 "Backspace".
  • 的字符串

RegEx 的:

  1. /[a-z]|$|#|\*/i: alpha
    • [a-z]:查找所有小写字母 az
    • |$|#|\*:包括您的 "allowed" 个字符,使用 | 作为 "OR" 分隔符。 $* 字符需要一个反斜杠,以便在 RegEx 语句中 转义 它们;否则它们具有完全不同的含义。
    • /i:这个小后缀告诉我们的 RegEx 忽略 字符的大小写。所以我们的开头语句不再关心它是小写还是大写。
  2. /[0-9]|\+|-/: 数字
    • [0-9]:查找每个数字,09
    • |\+|-:与字母表非常相似,这是您额外的 "allowed" 个字符,由 |(或)运算符分隔。
  3. /[a-z]|[0-9]|&/i: 字母数字
    • [a-z]:查找所有小写字母 az
    • |[0-9]:或者寻找每个数字,09
    • |&:再次检查您允许的字符。
    • /i:同样,忽略所有大小写问题。

示例 1:

$(document)
 .on('keydown', '.alpha', function(e) {
  var a = e.key;
  if (a.length == 1) return /[a-z]|$|#|\*/i.test(a);
  return true;
 })
 .on('keydown', '.numeric', function(e) {
  var a = e.key;
  if (a.length == 1) return /[0-9]|\+|-/.test(a);
  return true;
 })
 .on('keydown', '.alphanumeric', function(e) {
  var a = e.key;
  if (a.length == 1) return /[a-z]|[0-9]|&/i.test(a);
  return true;
 })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<hr />
<label for="inpAlpha">Alpha</label>
<input id="inpAlpha" type="text" char-allow="$#*" class="alpha" />
<hr />
<label for="inpNumeric">Num</label>
<input id="inpNumeric" type="text" char-allow="+-" class="numeric" />
<hr />
<label for="inpAlphaNum">Alpha Num</label>
<input id="inpAlphaNum" type="text" char-allow="&" class="alphanumeric" />
<hr />

或者将所有内容组合在一种方法中,示例 2

$(document)
 .on('keydown', 'input', function(e) {
  var a = e.key;
  if (a.length == 1) switch (true) {
   case $(this).hasClass('alpha'):
    return /[a-z]|$|#|\*/i.test(a);
    break;
   case $(this).hasClass('numeric'):
    return /[0-9]|\+|-/.test(a);
    break;
   case $(this).hasClass('alphanumeric'):
    return /[a-z]|[0-9]|&/i.test(a);
    break;
  }
  return true;
 })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<hr />
<label for="inpAlpha">Alpha</label>
<input id="inpAlpha" type="text" char-allow="$#*" class="alpha" />
<hr />
<label for="inpNumeric">Num</label>
<input id="inpNumeric" type="text" char-allow="+-" class="numeric" />
<hr />
<label for="inpAlphaNum">Alpha Num</label>
<input id="inpAlphaNum" type="text" char-allow="&" class="alphanumeric" />
<hr />



And, just for the heck of it, if you really do want a jQuery Plugin, I made a couple very simple ones. The first one is even more simplistic than the Plugin referred to by OP. See My Github for a bit more detailed info than below.

Most Simplistic Version:

第一个版本只有20行代码,甚至可以是minified to be much smaller [QuickLink]。它非常简单,因为您只需将 3 个 类 中的 1 个分配给任何输入 [ 'alpha', 'numeric', 'alphanumeric' ]。如果您想要允许额外的字符,那么只需添加 "allow" 的 HTML5 数据属性并为其指定允许的额外字符的值。
像这样:<input class="alpha" data-allow="$#*" type="text" />

;(function($) {
 var regEx = {
   alpha: new RegExp('[a-z]', 'i'),
   numeric: new RegExp('[0-9]'),
   alphanumeric: new RegExp('[a-z]|[0-9]', 'i')
  }
 function procInput(a, b, c) {
  switch(!0) {
   case a.hasClass('alpha'):
    return c ? 0 <= c.indexOf(b) || regEx.alpha.test(b) : regEx.alpha.test(b);
   case a.hasClass('numeric'):
    return c ? 0 <= c.indexOf(b) || regEx.numeric.test(b) : regEx.numeric.test(b);
   case a.hasClass('alphanumeric'):
    return c ? 0 <= c.indexOf(b) || regEx.alphanumeric.test(b) : regEx.alphanumeric.test(b);
  }
  return !0;
 }
 $(document).on('keydown', 'input', function(e) {
  var a = $(this), b = e.key, c = a.data('allow');
  return (!e.altKey && !e.ctrlKey) && 1 == b.length ? procInput(a, b, c) : !0;
 });
})(jQuery);

/* The following will "dynamically" make the second Alpha input an alpha only input 3 seconds after load is finished. This shows hwo the event assignment is versatile.  */
setTimeout(function() { $('#inpAlphaB').val('').addClass('alpha'); }, 3e3);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<hr />
<label for="inpAlpha">Alpha</label>
<input id="inpAlpha" type="text" data-allow="$#*" class="alpha" />
<hr />
<label for="inpAlphaB">Alpha B</label>
<input id="inpAlphaB" type="text" /> <sub>Is made "alpha" class 3 seconds after load.</sub>
<hr />
<label for="inpNumeric">Num</label>
<input id="inpNumeric" type="text" data-allow="+-" class="numeric" />
<hr />
<label for="inpAlphaNum">Alpha Num</label>
<input id="inpAlphaNum" type="text" data-allow="&" class="alphanumeric" />
<hr />

Extended Version:

这个版本有点复杂。仍然非常简单,因为您只需要分配 类 并使用 data-allow="string" 属性来允许额外的。然而,主要区别是这个版本有自己的 Object 可以 toggled 打开和关闭。它在第一行也有一个特性,允许您将其初始设置为 onoff基于第一个变量是true还是false。此版本还将自动在切换时清除字母|数字输入的值。

;(function($) { // $.inputAlphaNumeric // set first variable "initializeON" to bool to toggle on || off from document.ready
 var initializeON = true;
 
 function __event(e) {
  return $.inputAlphaNumeric.keydown.event.apply($.inputAlphaNumeric, [e, this]);
 }
 
 function adjustValue() { // clean up inputs when feature is toggled 'on'
  if (this.state) {
   var regEx = this.regEx;
   this.inputs.each(function() {
    var a = $(this), b = a.val(), c = a.data('allow');
    if (b != '') switch(!0) {
     case $(this).hasClass('alpha'):
      a.val( b.split('').filter(function(v) { if ((c && 0 <= c.indexOf(v)) || regEx.alpha.test(v)) return v; }).join('') );
      break;
     case $(this).hasClass('numeric'):
      a.val( b.split('').filter(function(v) { if ((c && 0 <= c.indexOf(v)) || regEx.numeric.test(v)) return v; }).join('') );
      break;
     case $(this).hasClass('alphanumeric'):
      a.val( b.split('').filter(function(v) { if ((c && 0 <= c.indexOf(v)) || regEx.alphanumeric.test(v)) return v; }).join('') );
      break;
    }
   });
  }
  return this;
 }
 
 function keyDown() {
  return { event: keyDownEvent, process: keyDownProcess }
 }
 function keyDownEvent(e, inp) {
  var a = $(inp), b = e.key, c = a.data('allow');
  return (!e.altKey && !e.ctrlKey) && 1 == b.length ? this.keydown.process.apply(this, [a, b, c]) : !0;
 }
 function keyDownProcess(a, b, c) {
  var regEx = this.regEx;
  switch(!0) {
   case a.hasClass('alpha'):
    return c ? 0 <= c.indexOf(b) || regEx.alpha.test(b) : regEx.alpha.test(b);
   case a.hasClass('numeric'):
    return c ? 0 <= c.indexOf(b) || regEx.numeric.test(b) : regEx.numeric.test(b);
   case a.hasClass('alphanumeric'):
    return c ? 0 <= c.indexOf(b) || regEx.alphanumeric.test(b) : regEx.alphanumeric.test(b);
  }
  return !0;
 }
 
 function inputAlphaNumeric(initOn) {
  Object.defineProperties(this, {
   __state: { enumerable: false, value: false, writable: true },
   adjustVal: {
    enumerable: false,
    value: adjustValue,
    writable: false
   },
   classes: { enumerable: true, get: function() { return [ 'alpha', 'numeric', 'alphanumeric' ]; } },
   inputs: { enumerable: true, get: function() { return $(this.selector); } },
   keydown: { enumerable: false, get: keyDown },
   off: { value: function() { return this.toggle('off'); } },
   on: { value: function() { return this.toggle('on'); } },
   regEx: {
    enumerable: true,
    get: function() {
     return {
      alpha: new RegExp('[a-z]', 'i'),
      numeric: new RegExp('[0-9]'),
      alphanumeric: new RegExp('[a-z]|[0-9]', 'i')
     }
    }
   },
   selector: { enumerable: true, get: function() { return '.' + this.classes.join(', .'); } },
   state: {
    get: function() { return this.__state; },
    set: function(onOff) {
     switch (typeof onOff) {
      case 'boolean':
       this.__state = onOff
       break;
      case 'string':
       switch (onOff) {
        case 'on':
         this.__state = true;
         break;
        case 'off':
         this.__state = false;
         break;
        default:
         this.__state = true;
       }
       break;
      default:
       this.__state = true;
     }
     return this;
    }
   },
   toggle: {
    value: function(onOff) {
     this.state = void 0 == onOff ? !this.state : onOff;
     $(document)[this.state ? 'on' : 'off']('keydown', 'input', __event);
     return this.adjustVal();
    }
   }
  });
  if (initOn) this.on();
  return this;
 }
 
 $.inputAlphaNumeric = new inputAlphaNumeric(initializeON);
})(jQuery);

// checkbox to toggle feature on and off
$(document).on('change', '[type=checkbox]', function(e) { var a = $.inputAlphaNumeric.toggle(this.checked); if (window['console'] && console.debug) console.debug(a); });
// sets initial state of checkbox based on whether or not feature is on or off
$('[type=checkbox]').prop('checked', $.inputAlphaNumeric.state);

setTimeout(function() { $('#inpAlphaB').val('').addClass('alpha'); }, 3e3);

$.each($.inputAlphaNumeric, function(k,v) { console.debug(k + ":\t", v); });
console.debug("$.inputAlphaNumeric:\t", $.inputAlphaNumeric);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<label for="inpAlpha">Alpha</label>
<input id="inpAlpha" type="text" data-allow="$#* " class="alpha" /><!--Notice I added a "space" value as well-->
<hr />
<label for="inpAlphaB">Alpha B</label>
<input id="inpAlphaB" type="text" /> <sub>Is made "alpha" class 3 seconds after load.</sub>
<hr />
<label for="inpNumeric">Num</label>
<input id="inpNumeric" type="text" data-allow="+-" class="numeric" />
<hr />
<label for="inpAlphaNum">Alpha Num</label>
<input id="inpAlphaNum" type="text" data-allow="&" class="alphanumeric" />
<hr />
<label for="inpAlphaNumToggle">Alpha Num</label>
<input id="inpAlphaNumToggle" type="checkbox" />
<hr />