【问题标题】:Is there a simple way to trigger form validation onSubmit instead of onLoad with bootstrap and Vue.Js?有没有一种简单的方法来触发表单验证 onSubmit 而不是使用 bootstrap 和 Vue.Js 的 onLoad?
【发布时间】:2019-03-17 19:54:45
【问题描述】:

我有一个密码重置表单,最初当然是空的,我想在提交时验证所有字段都不是空的。我正在为每个字段执行以下操作:

    <b-form-group id="currentPassword" 
              label="Old password"
              :invalid-feedback="oldPasswordFeedback">
        <b-form-input id="password" 
                      v-model="passwords.currentPassword" 
                      placeholder="Enter your old Password" 
                      type="password"  
                      maxlength="60" 
                      required/>
    </b-form-group>

表格是这样定义的

  <b-form validated="" id="passwordChangeForm" @submit.prevent="changePassword" class="container-fluid">

问题是每当我导航到该页面时,所有字段都默认标记为无效并显示它们的错误消息,因为它们是空的。我希望在提交表单时进行验证。有没有一种无需安装额外验证插件的简单方法?

【问题讨论】:

    标签: javascript vue.js vuejs2 vue-component bootstrap-vue


    【解决方案1】:

    在您的组件声明中,您设置了required 属性,该属性会在您加载页面时尝试验证您的表单,因此您可以利用Vue.js 并在最初的数据对象中创建req 属性设置为false

    我提供以下简化示例来向您展示如何做到这一点

    new Vue({
      el: '#app',
    
      data() {
        return {
        item:'',
         currentPassword:'',
         req:false
        }
      },
      methods: {
      changePassword: function() {
        this.req=true;
        }
      }
    
    });
    <link type="text/css" rel="stylesheet" href="//unpkg.com/bootstrap/dist/css/bootstrap.min.css" />
    <link type="text/css" rel="stylesheet" href="//unpkg.com/bootstrap-vue@latest/dist/bootstrap-vue.css" />
    
    <!-- Add this after vue.js -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>
    <script src="//unpkg.com/babel-polyfill@latest/dist/polyfill.min.js"></script>
    <script src="//unpkg.com/bootstrap-vue@latest/dist/bootstrap-vue.js"></script>
    
    
    <div id="app" class="container">
      <div>
        
        <b-form validated="" id="passwordChangeForm" @submit.prevent="changePassword" class="container-fluid">
          <b-form-group id="currentPassword" label="Old password">
            <b-form-input id="password" v-model="currentPassword" placeholder="Enter your old Password" type="password" :required="req" />
          </b-form-group>
          <b-button type="submit" variant="primary">Submit</b-button>
        </b-form>
      </div>
    </div>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多