验证输入字段的特定结构

Validate specific structure of input field

我真的需要这方面的帮助...我有一个输入字段需要非常具体的验证。这些是规则:

  1. 最多 5 个字符(但可以更少)
  2. 前 4 个字符只能是数字,第五个字符必须是字母。

到目前为止,我已经设法验证了长度,并测试了整个字符串的数字。 我想不通的是如何只测试字符串的一部分(以及另一部分的文本)

这是我使用的代码:

$(document).ready(function() {
    $('.input-text').on('change', function() { 
        if ($(this).val().length>5) {
            alert( 'Sorry... Maximum of 5 characters allowed' );
            var res = $(this).val().substring(0, 4);
            $(this).val(res);
        }

        if ( $(this).val() &&  !$(this).isNumeric ) {
            alert("Numbers Only Please");
            $(this).val('');
        }
    })
});

提前致谢

一个选项是从字符串中切出第 0 到第 3 个和第 4 个字符,然后检查第一个字符是否匹配 ^\d*$(所有数字),最后一个字符(如果存在)匹配 [a-z](按字母顺序):

$('.input-text').on('change', function() {
  const val = $(this).val();
  if (val.length > 5) {
    console.log('Sorry... Maximum of 5 characters allowed');
    $(this).val(val.slice(0, 4));
  }
  const firstFour = val.slice(0, 4);
  const fifth = val[4];
  if (!/^\d*$/.test(firstFour)) {
    console.log('First four must be numeric only');
    $(this).val('');
    return;
  }
  if (fifth && !/[a-z]/i.test(fifth)) {
    console.log('Fifth must be alphabetical');
    $(this).val(firstFour);
  }
})
<input class="input-text">

也可以在单个正则表达式中完成,但是您无法区分输入可能存在的不同类型的问题。

此外,不需要 jQuery 对于这种微不足道的事情,您可以删除对它的依赖 并且 如果您愿意,可以使语法看起来更简洁:

document.querySelector('.input-text').addEventListener('change', function() {
  const val = this.value
  if (val.length > 5) {
    console.log('Sorry... Maximum of 5 characters allowed');
    this.value = val.slice(0, 4);
  }
  const firstFour = val.slice(0, 4);
  const fifth = val[4];
  if (!/^\d*$/.test(firstFour)) {
    console.log('First four must be numeric only');
    this.value = '';
    return;
  }
  if (fifth && !/[a-z]/i.test(fifth)) {
    console.log('Fifth must be alphabetical');
    this.value = firstFour;
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="input-text">

你可以做到这一点..

$(document).ready(function() {
$('.input-text').on('change', function() { 
    if ($(this).val().length>5) {
        alert( 'Sorry... Maximum of 5 characters allowed' );
        var res = $(this).val().substring(0, 4);
        $(this).val(res);
    }

     var value2 = $(this).val().substr(0,4);

     if (value2 &&  !value2.isNumeric ) {
        alert("Numbers Only Please");
        $(this).val('');
     }

     var res = str.charAt(4)
     var key = res.keyCode;
     if (key >= 65 && key <= 90) {
        alert('Sorry... Please enter Last character alphabetically')
     }
    })
  });