JS judge the length of input string example code of Chinese characters count two characters alphanumeric count one

  • 2021-07-07 06:06:48
  • OfStack

js Example code for judging the length of input string (two characters for Chinese characters and one for alphanumeric characters)

This method of validation was thought of when text was entered because the database table field length limit would cause the submission to fail.

Don't talk too much about the code:


<html>
<head>
  <title>js Judge the length of the input string (two characters for Chinese characters and alphanumeric characters) 1 A) </title>
  <style type="text/css">
    .pbt {
      margin-bottom: 10px;
    }

    .ie6 .pbt .ftid a, .ie7 .pbt .ftid a {
      margin-top: 1px;
    }

    .cl:after {
      clear: both;
      content: ".";
      display: block;
      height: 0;
      visibility: hidden;
    }
  </style>
  <script type="text/javascript">
    // Get the length of the string (two characters for Chinese characters and alphanumeric characters) 1 A) 
    function getByteLen(val) {
      var len = 0;
      for (var i = 0; i < val.length; i++) {
        var a = val.charAt(i);
        if (a.match(/[^\x00-\xff]/ig) != null) {
          len += 2;
        }
        else {
          len += 1;
        }
      }
      return len;
    }
    //  Just the keyboard 1 Verify the text length in the edit box by lifting it. The maximum character length can be set as needed 
    function checkLength(obj) {
      var maxChars = 80;// Maximum number of characters    
      var curr = maxChars - getByteLen(obj.value);
      if (curr > 0) {
        document.getElementById("checklen").innerHTML = curr.toString();
      } else {
        document.getElementById("checklen").innerHTML = '0';
        document.getElementById("subject").readOnly = true;
      }
    }
  </script>
</head>
<body>
  <div class="pbt cl">
    <textarea id="subject" maxlength="80" onkeyup="checkLength(this)" accesskey="1" tabindex="11"></textarea>
    <span id="subjectchk"> You can also enter 
    <strong id="checklen" style="color: #FF0000">80</strong>
       Characters 
    </span>
    <span id="postNameRule" class="spn_flag_1" style="display: none"></span>
  </div>
</body>
</html>

Related articles: