HTML
CSS
JavaScript
HTML
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>文本框 - 使用 JavaScript 进行表单验证</title>
  <link rel="stylesheet" href="https://cdn.w3cbus.com/library/mdui/1.0.2/css/mdui.min.css"/>
</head>
<body class="mdui-theme-primary-indigo mdui-theme-accent-pink">

  <div class="mdui-container">
    <div class="mdui-textfield" id="textfield">
      <label class="mdui-textfield-label">User name</label>
      <input class="mdui-textfield-input" id="input" type="text"/>
      <div class="mdui-textfield-error" id="error">用户名已存在</div>
    </div>

    <button class="mdui-btn mdui-color-theme-accent" id="valid">验证</button>
  </div>

  <script src="https://cdn.w3cbus.com/library/mdui/1.0.2/js/mdui.min.js"></script>
</body>
</html>
CSS

  
JavaScript
var $ = mdui.$;

var $textfield = $('#textfield');
var $input = $('#input');
var $error = $('#error');
var hasError = false;

$('#valid').on('click', function () {
  var value = $input.val();

  if (value.length < 6) {
    $error.text('用户名不能小于 6 位');
    hasError = true;
  } else if (value.length > 20) {
    $error.text('用户名不能超过 20 位');
    hasError = true;
  } else {
    hasError = false;
  }

  if (hasError) {
    $textfield.addClass('mdui-textfield-invalid');
  } else {
    $textfield.removeClass('mdui-textfield-invalid');
  }
});