How To Verify Mobile Number In Vue JS

Without utilising an outside package, Vue.js allows you to quickly validate a phone number. You may use the code I’ve provided below to understand how to accomplish it without utilising any NPM packages:

Here is my App.vue component that does the validation:

<template>
  <div id="app" class="text-center">
    <label for="phoneNumber"> Enter phone number </label>
    <input name="phoneNumber" :class="{ valid: isValidPhoneNumber, invalid: !isValidPhoneNumber }" v-model="phoneNumber"
      type="text" @keyup="validatePhoneNumber" />
    <div class="warning" v-if="!isValidPhoneNumber">
      Please Enter Valid Phone Number
    </div>
    <div class="np-credits">wwww.visioninfotech.com</div>
  </div>
</template>

<script>
export default {
  name: 'app',
  data() {
    return {
      phoneNumber: '',
      isValidPhoneNumber: true,
    }
  },
  methods: {
    validatePhoneNumber() {
      const validationRegex = /^\d{10}$/;
      if (this.phoneNumber.match(validationRegex)) {
        this.isValidPhoneNumber = true
      } else {
        this.isValidPhoneNumber = false
      }
    }
  }
}
</script>

<style>
#app {
  font-family: "Avenir", Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  padding: 24px;
}

.np-credits {
  font-size: 12px;
  margin-top: 12px;
  color: #4b4b4b;
}

label {
  font-size: 20px;
  display: block;
  margin: 10px auto;
  font-weight: 600;
}

input {
  display: block;
  outline: none;
  border: 2px solid #eee;
  font-size: 20px;
  padding: 10px;
  background: #eee;
  border-radius: 6px;
}

.invalid {
  border: 2px solid #fe9696;
}

.valid {
  border: 2px solid #9ef19e;
}

.warning {
  margin: 10px auto;
  color: red;
  font-size: 12px;
}

input {
  margin: 0 auto !important;
}
</style>

I’m utilising two reactive states in the code above:

  • phoneNumber: The user-supplied number to be used with the V-model.
  • isValidPhoneNumber: Indicates if the entered phone number is legitimate.

The validatePhoneNumber function will be called each time the user pushes a key. Using this function, you may determine whether or not the provided phone number conforms to the validationRegex format.

Whatever regex you wish to use to verify the phone number may be created.

If the user provides a genuine phone number, this function will set isValidPhoneNumber to true. If false, the procedure will set its value if anything else.

If the result of isValidPhoneNumber is false, we have finally showed the message “Invalid phone number!”

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories