【问题标题】:Error when validating password with regex value?使用正则表达式值验证密码时出错?
【发布时间】:2021-06-12 11:56:16
【问题描述】:

使用 1 个大写字母和 1 个小写字母 1 个数字 1 个特殊字符进行验证时,密码验证不起作用。

methods: {
    validateBeforeSubmit() {
      this.$validator.localize('en', dict)
      this.$validator.validateAll()
      .then(function(response){
        
      })
      .catch(function(e){
        
      })
    }
  }
<form class="center-container" @submit.prevent="validateBeforeSubmit()">
<input
:type="passwordFieldType"
v-model="user.password"
v-model.trim="$v.user.password.$model"
id="password"
 name="password"
class="input-section-three-login"
:class="{'is-invalid': validationStatus($v.user.password) }"                  
placeholder="Enter new password"
v-on:keypress="isPassword($event)" ref="password"
v-validate="{ required: true, min: 10, regex: /^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$%^&*-]).*$/ }"/>


 <input
:type="passwordFieldTypetwo"
v-model="user.confirmPassword"
id="confirmPassword"
name="confirmPassword"
class="input-section-three-login"
:class="{
 'is-invalid': submitted && $v.user.confirmPassword.$error,
}"
 placeholder="Confirm password"
:maxlength="maxconfirmpassword"
v-on:keypress="isconfirmPassword($event)"
:disabled="user.password.length < 8"
v-validate="'confirmPassword'" data-vv-as="password"/>
                
                
 <button  class="register-button-screen2"v-on:click="registerMe"
:disabled="user.confirmPassword != user.password   "
:class="(isDisabled) ? '' : 'selected'">Register</button>
                    
                    
                    
<div class="alert alert-danger" v-show="errors.any()">
<div v-if="errors.has('password')">
{{ errors.first('password') }}
</div>
<div v-if="errors.has('password_confirmation')">
{{ errors.first('password_confirmation') }}
</div>
</div>
</form>

使用 1 个大写字母和 1 个小写字母 1 个数字 1 个特殊字符进行验证时,密码验证不起作用。

【问题讨论】:

    标签: javascript regex vue.js vee-validate


    【解决方案1】:

    您不能真正使用正则表达式进行这种验证,因为字符可以按任何顺序排列。

    相反,您应该创建一个自定义验证规则来对输入字符串执行每次检查:

    import { Validator } from 'vee-validate'
    
    Validator.extend('password', {
      getMessage: (field) =>
        'The ' + field + ' value must contain 1 uppercase, 1 lowercase, 1 number, and 1 special character.',
      validate: value => {
        return (
          /[A-Z]/.test(value) &&
          /[a-z]/.test(value) &&
          /\d/.test(value) &&
          /[!@#$%^&*()_\-+=`~<>?\\/;,.'"\][{}]/.test(value)
        )
      }
    })
    

    用法:

    <input v-validate="{ password: true }">
    

    demo

    【讨论】:

    • 我们能不能把它当作 v-on:keypress="isPassword($event)" 并为它写一个方法。
    • 技术上可行,但isPassword() 只是检查输入的值,这实际上是在重复vee-validate 的工作。为什么不使用vee-validate
    猜你喜欢
    • 2021-02-27
    • 1970-01-01
    • 2021-10-17
    相关资源
    最近更新 更多