如何在 vee 验证 3.0 版本中验证十进制值

Kru*_*hah 3 vue.js vuejs2

我想验证纬度和经度值,我的代码是

    <ValidationProvider :name=waypointLang.form.latitude rules="required|decimal">
        <div slot-scope="{ errors }">
            <input v-model="waypoint.latitude" readonly name="latitude" type="text" autofocus :placeholder="waypointLang.form.latitude" class="form-control" id="latitude"/>
                   <span class="required-field">{{ errors[0]}}</span>
        </div>
    </ValidationProvider>
Run Code Online (Sandbox Code Playgroud)

我收到错误不存在这样的验证器“十进制”。

提前致谢

小智 6

您可以通过将其添加到您的 ./plugins/vee-validate.js 文件来添加自定义规则:

extend("decimal", {
  validate: (value, { decimals = '*', separator = '.' } = {}) => {
    if (value === null || value === undefined || value === '') {
      return {
        valid: false
      };
    }
    if (Number(decimals) === 0) {
      return {
        valid: /^-?\d*$/.test(value),
      };
    }
    const regexPart = decimals === '*' ? '+' : `{1,${decimals}}`;
    const regex = new RegExp(`^[-+]?\\d*(\\${separator}\\d${regexPart})?([eE]{1}[-]?\\d+)?$`);

    return {
      valid: regex.test(value),
    };
  },
  message: 'The {_field_} field must contain only decimal values'
})
Run Code Online (Sandbox Code Playgroud)