• 限制字符串长度


    在开发web页面时,表单内字符串过长而超出规定长度会导致一些不必要的麻烦,
    比如:
         用户注册时系统限制的用户名只有8个英文字符,但是用户输入了10个或者更多的字符时,
    就可能造成昵称页面显示错行,或者昵称被截断的问题。
    下面是限制字符串长度的解决方案:
    1,通过使用JavaScript原生的获取属性的方法:
    #id.getAttribute("data-length");

    来判断输入框的限制长度。

    2,通过比对输入的长度与输入框的限制长度属性进行比较:

    if(输入长度 > 属性长度){
      value = value.substr(0,属性长度); //超过长度自动截取  
    }

    HTML代码:

    <input type="text" data-length="6" id="limitLength" name="Iname"/>

    JavaScript方法:

    var  maxLength = function(tThis){
        var _v = tThis.value.replace(maxRegex,''), //获取输入文本(去除空格)
        _vLen = _v.length,
        dataLength = tThis.getAttribute('data-length'), //获取限制长度
        dataModel = tThis.getAttribute('data-model'),
        subLen = dataLength;
                        
        if(_vLen > dataLength){
        tThis.value = _v.substr(0,subLen);  //判断长度,超过长度自动截取
        }
    }

    完整的javaScript代码:

    var limitLength = document.getElementById('limitLength');
                var maxRegex = /s+/g;//去除空格的正则表达式
                var  maxLength = function(tThis){
                    var _v = tThis.value.replace(maxRegex,''), //获取输入文本(去除空格)
                        _vLen = _v.length,
                        dataLength = tThis.getAttribute('data-length'), //获取限制长度
                        dataModel = tThis.getAttribute('data-model'),
                        subLen = dataLength;
                        
                    if(_vLen > dataLength){
                        tThis.value = _v.substr(0,subLen);  //判断长度,超过长度自动截取
                    }
                }
                
                limitLength.onblur = function(){
                    maxLength(this);
                }
                
                limitLength.onkeyup = function(){
                    maxLength(this);
                }
                
                limitLength.onfocus = function(){
                    maxLength(this);
                }
    View Code

    如果您感兴趣,请点一下推荐额,谢谢!

    扫码关注微信公众号:

  • 相关阅读:
    Eureka与Zookeeper的区别
    Eureka的集群配置
    Rest微服务案例
    Eureka概述
    SpringCloud与Dubbo区别对比
    各种微服务框架对比
    ElasticSearch(九):elasticsearch-head插件安装
    ElasticSearch(八):elasticsearch.yml配置说明
    Docker(2):使用Dockerfile创建支持SSH服务的镜像
    CentOS 7 安装Kubernetes(单机版)
  • 原文地址:https://www.cnblogs.com/White-Quality/p/5518666.html
Copyright © 2020-2023  润新知