How to validate Vuetify text field asynchronously?

后端 未结 2 1723
走了就别回头了
走了就别回头了 2021-02-09 01:42

Text fields in Vuetify have rules props, which take an array of functions returning true or an error string. How to make them async, so that the valida

2条回答
  •  时光取名叫无心
    2021-02-09 02:09

    I have to do a backend validation to check if the username entered already exists. I use the swagger client library with the JSON open API v3 to call the method that checks the username value.

    So I solved in this way...

    In my login.js file I have defined a string property that contains the error message:

    import swaggerClient from "../remote-client";
    const strict = true;
    const state = {
      hasError: false,
      error: null,
      usernameAlredyExists: ""
    };
    const getters = {
      hasError: state => state.hasError,
      error: state => state.error,
      usernameAlredyExists: state => state.usernameAlredyExists
    };
    const mutations = {
      checkingUsername(state) {
        state.hasError = false;
        state.error = null;
        state.usernameAlredyExists = "";
      },
      usernameCheckedKO(state) {
        state.usernameAlredyExists = "Username already exists";
      },
      usernameCheckedOK(state) {
        state.usernameAlredyExists = "";
      },
      errorCheckingUsername(state, error) {
        state.hasError = true;
        state.error = error;
      },
    };
    const actions = {
      userLogin({ commit }, { username, password }) {
        // not relevant code
      },
      checkUsername({ commit }, { username }) {
        commit("checkingUsername");
        swaggerClient.userSwaggerClient
          .then(
            function(client) {
              return client.apis.UserHealthFacility.getHfUserUsernameWithUsername(
                { username: username },
                {},
                {}
              );
            },
            function(reason) {
              // failed to load the JSON specification
              commit("errorCheckingUsername", reason);
            }
          )
          .then(
            function(callResult) {
              if (callResult.body) {
                commit("usernameCheckedKO");
              } else {
                commit("usernameCheckedOK");
              }
            },
            function(reason) {
              // failed to call the API method
              commit("errorCheckingUsername", reason);
            }
          );
      }
    };
    
    export default {
      namespaced: true,
      strict,
      state,
      getters,
      mutations,
      actions
    };
    

    Then in the Login.vue file I have this code:

    
      
        
        
      
    
    
      
      Login
    
    
    
    

    In this way it seems to work well

提交回复
热议问题