css Audio - Active file-generic CSS - Active Generic - Active HTML - Active JS - Active SVG - Active Text - Active file-generic Video - Active header Love html icon-new-collection icon-person icon-team numbered-list123 pop-out spinner split-screen star tv

Pen Settings

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

You're using npm packages, so we've auto-selected Babel for you here, which we require to process imports and make it all work. If you need to use a different JavaScript preprocessor, remove the packages in the npm tab.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Use npm Packages

We can make npm packages available for you to use in your JavaScript. We use webpack to prepare them and make them available to import. We'll also process your JavaScript with Babel.

⚠️ This feature can only be used by logged in users.

Code Indentation

     

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

HTML Settings

Here you can Sed posuere consectetur est at lobortis. Donec ullamcorper nulla non metus auctor fringilla. Maecenas sed diam eget risus varius blandit sit amet non magna. Donec id elit non mi porta gravida at eget metus. Praesent commodo cursus magna, vel scelerisque nisl consectetur et.

            
              <form action="" id="registerForm" method="post">
  请输入用户名: <input type="text" name="userName" value="12345"><br>
  请输入密码: <input type="password" name="password" value="123456"><br>
  请输入手机号码: <input type="phone" name="phoneNumber" value="13751146374"><br>
  
  <input type="submit">
</form>
            
          
!
            
              let registerForm = document.getElementById("registerForm");

const Rules = {
  longerThan6: val => val && val.length >= 6,
  isPhone: val => val && /(^1[3|5|8][0-9]{9}$)/.test(val),
  notEmpty: val => val && val.length != 0
};
let { longerThan6, isPhone, notEmpty } = Rules;

let validate = () => {
  let validator = new Validator();

  // 一次添加多个规则
  validator.add(registerForm.userName, [
    {
      validateFunc: val => val.length >= 6,
      errorMessage: "用户名长度不可小于六位"
    },
    { validateFunc: notEmpty, message: "用户名不能为空" }
  ]);

  // 一次添加单个规则
  validator.add(registerForm.password, longerThan6, "密码长度必须大于6位");
  validator.add(registerForm.phoneNumber, isPhone, "电话号码格式错误");

  // 开始校验,成功则返回false,失败则返回对应的errorMessage。
  return validator.start();
};

registerForm.onsubmit = () => {
  let errorMessage = validate();
  if (errorMessage) {
    alert(errorMessage);
    return false;
  }
};

class Validator {
  rules = [];
  constructor() {
    this.rules = [];
  }

  /**
   * 该方法负责添加验证规则。
   * 该函数接受三个参数,第一个参数是input元素(Element)
   * 第二个参数可能是数组或函数,若第二个参数是数组,忽略第三个参数,
   * 且该数组的元素结构必须是{validateFunc: Function, errorMessage: String}。
   *
   * @param {Element} inputElement
   * @param {Array | Function} rules
   * @param {String} message
   * @memberof Validator
   */

  add(inputElement, rules, errorMessage) {
    let val = inputElement.value;

    // 如果第二个参数是函数,那就是用于验证的函数咯。
    if (typeof rules === "function") {
      let validateFunc = rules; // 没啥意义的赋值,为了你更好的理解。

      this.rules.push({
        value: val,
        validateFunc: validateFunc,
        errorMessage: errorMessage
      });
      return;
    }

    // 如果第二个参数是数组,那就是一组规则,忽略第三个参数。
    if (Array.isArray(rules)) {
      for (let rule of rules) {
        this.rules.push({
          value: val,
          validateFunc: rule.validateFunc,
          errorMessage: rule.errorMessage
        });
      }
      return;
    }
  }

  start() {
    for (let rule of this.rules) {
      let { value, validateFunc, errorMessage } = rule;
      if (!validateFunc(value)) {
        return errorMessage;
      }
    }
    return false;
  }
}

            
          
!
999px
🕑 One or more of the npm packages you are using needs to be built. You're the first person to ever need it! We're building it right now and your preview will start updating again when it's ready.
Loading ..................

Console