使用者名稱不可為空

來源:互聯網
上載者:User

標籤:

在表單中經常些必填項目,如果使用者沒有輸入則不允許提交表單。例如在註冊使用者時,必須填寫使用者名稱才能提交註冊資訊。驗證使用者是否輸入時,通常需要先過濾再驗證(如果使用者輸入的都是空格就相當於沒有輸入)。我們通過使用Regex匹配空格
1 var regex = /\s+/g;
調用string的replace方法清除空格
1 string.replace(regex,‘‘);
建立一個函數:
1 function regexEmpty(obj){2      obj.value = obj.value.replace(regex,‘‘);3 }

具體代碼如下:

HTML:

1 < div class= "main">2            < input id= "userName" type= "text" placeholder= "請輸入使用者名稱" >3            < input id= "rule" type= "button" value= "驗證">4 </ div>

 

css:

1 html,body ,div, input{margin :0; padding:0 ;}2             .main{width :400px ;height: auto;padding :0 15px; text-align:center; }3             .main input{width :100% ;height: 35px; border:none ;margin-top: 20px; border-radius:5 px;}4            input[type ="text"] {text-align: left;padding-left :15px ;box-sizing: border-box;border :1px solid green; }5             input[type ="button"] {width: 50%; background:green; }

javascript:

 1 var userName = document.getElementById(‘userName‘ ), 2                 rule  = document.getElementById( ‘rule‘), 3                 deleteEmpty = null, 4                 regex    = /\s+/g; 5             deleteEmpty = function (obj){ 6                 obj.value = obj.value.replace(regex,‘‘ ); 7                  if(! obj.value){ 8                      alert( ‘使用者名稱不可為空‘ ); 9                 } else{10                         alert(‘pass‘);11                 }12            }13            rule. onclick = function (){14                 deleteEmpty(userName);15 };

demo示範地址:點擊這裡

使用者名稱不可為空

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.