Home > other >  make a rule about input to accept empty string and specific number of chars
make a rule about input to accept empty string and specific number of chars

Time:09-08

How can I make a rule about input to accept only two condition:

  • the input must be only 5 chars.
  • the input can accept empty string.

What I've did so far:

new Vue({
  el: '#app',
 data: () => ({
   code:"",
   rules: {
        codeRules: (v) =>(v ?? "").trim().length == 5 ||"code must be 5 chars!"
   }
 }),
 methods: {
    checkCode(){
      if (this.$refs.form.validate()) {
          alert('Everything goes well!')
      }
    }
 }
})
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/vuetify.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vuetify.min.js"></script>

<div id="app">
  <v-app>
    <v-form ref="form" lazy-validation>
      <v-container bg fill-height grid-list-md text-xs-center>
         <v-row>
            <v-col cols="6">
              <v-text-field
                label="Code"
                v-model="code"
                :rules="[rules.codeRules]"
              ></v-text-field>
            </v-col>
         </v-row>
         <v-row>
            <v-col cols="6">
              <v-btn color="blue darken-1" @click="checkCode">Ok
          </v-btn>
            </v-col>
         </v-row>
      </v-container>
    </v-form>
  </v-app>
</div>

First condition I've accomplish, BUT How can I let the input accept also empty string!

CodePudding user response:

You can use a simple logical expression:

The input ins valid when it's a string and it is the empty string or it is a string with 5 characters.

Moving that into code will give you the following:

const isValid = (input) => typeof(input) === "string" && input === "" || input.length === 5;

console.log(isValid(""))
console.log(isValid("chars"))
console.log(isValid("invalid"))
console.log(isValid(1))
console.log(isValid([]))
console.log(isValid({}))
.as-console-wrapper { max-height: 100% !important; top: 0; }

In Vue you can use that function isValid():

new Vue({
  el: '#app',
  data(){
    return {
      code: "",
      rules: {
        codeRules: (v) => this.isValid(v) ? "" : "must be either empty or 5 chars long!",
      }
    };
  },
  methods: {
    checkCode(){
      if (this.$refs.form.validate()) {
        alert('Everything goes well!')
      }
    },
    isValid(v){
      return typeof(v) === "string" && v === "" || v.length === 5
    }
  }
})
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/vuetify.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vuetify.min.js"></script>

<div id="app">
  <v-app>
    <v-form ref="form" lazy-validation>
      <v-container bg fill-height grid-list-md text-xs-center>
        <v-row>
          <v-col cols="6">
            <v-text-field label="Code" v-model="code" :rules="[rules.codeRules]"></v-text-field>
          </v-col>
        </v-row>
        <v-row>
          <v-col cols="6">
            <v-btn color="blue darken-1" @click="checkCode">Ok
            </v-btn>
          </v-col>
        </v-row>
      </v-container>
    </v-form>
  </v-app>
</div>

You could of course also return a dedicated error message for each case but you get the gist of it I hope so you can implement that if you want to.

  • Related