21

由于 vue-validator https://github.com/vuejs/vue-validator已经为 Vuejs 2 做好了准备,那么实现前端验证的最佳方式是什么?

更新我发现了这个很棒的插件 Vee Validate

4

5 回答 5

3

在我看来,为 VueJS 实现前端验证的一个好方法是使用vuelidate

它使用起来非常简单且功能强大。它提供基于模型的验证,这意味着它是您在验证的数据中定义的内容,因此它与模板完全分离。它带有用于电子邮件、最小和最大长度或必需的通用内置验证器。还有许多其他人。

于 2018-03-27T13:20:40.193 回答
2

由于最终都是 Javascript,您还可以使用一些现有的 Javascript 验证库,如Parsely.jsValidate.js来连接它。Validate.js 库的一个优点是,如果您使用 Vuex,它的格式可以很容易地存储在全局存储中:

var constraints = {
  creditCardNumber: {
    presence: true,
    format: {
      pattern: /^(34|37|4|5[1-5]).*$/,
      message: function(value, attribute, validatorOptions, attributes, globalOptions) {
        return validate.format("^%{num} is not a valid credit card number", {
          num: value
        });
      }
    },
    length: function(value, attributes, attributeName, options, constraints) {
      if (value) {
        // Amex
        if ((/^(34|37).*$/).test(value)) return {is: 15};
        // Visa, Mastercard
        if ((/^(4|5[1-5]).*$/).test(value)) return {is: 16};
      }
      // Unknown card, don't validate length
      return false;
    }
  },
  creditCardZip: function(value, attributes, attributeName, options, constraints) {
    if (!(/^(34|37).*$/).test(attributes.creditCardNumber)) return null;
    return {
      presence: {message: "is required when using AMEX"},
      length: {is: 5}
    };
  }
};

然后这样使用:

validate({creditCardNumber: "4"}, constraints);
// => {"creditCardNumber": ["Credit card number is the wrong length (should be 16 characters)"]}

validate({creditCardNumber: "9999999999999999"}, constraints);
// => {"creditCardNumber": ["9999999999999999 is not a valid credit card number"]}

validate({creditCardNumber: "4242424242424242"}, constraints);
// => undefined

validate({creditCardNumber: "340000000000000"}, constraints);
// => {"creditCardZip": ["Credit card zip is required when using AMEX"]}

您还可以将这些 validate() 函数与您的组件挂钩,类似于@blur=validate(...)

于 2016-11-23T05:35:07.003 回答
1

如果您使用语义 UI 或它是您的一个选项,他们有一个很棒的表单验证插件。

语义-ui-form-validation

我已经将它与 Vuejs 一起使用,并且效果很好。

于 2016-11-22T19:39:10.617 回答
1

目前没有太多选择。看看vue-awesome,你可以在其中找到最相关的库。目前有2个。

于 2016-10-24T13:38:21.840 回答
0

我发现这个验证器简单、灵活并且有据可查。它涵盖了 Vue Js 中验证表单的大多数场景。

我过去使用过 Jquery 验证器插件。与此相比,这个 simple-vue-validator 确实在其灵活性和验证硬编码和动态生成的表单的能力方面脱颖而出。

https://github.com/semisleep/simple-vue-validator

我将它广泛用于我的 SaaS 项目,到目前为止它运行得非常好。

于 2017-02-10T08:39:52.247 回答