Vuetify rule for Number Between 0 and 999 or no input

Vuetify is a popular Material Design component framework for Vue.js applications, offering a wide range of features for creating beautiful and functional user interfaces. One common requirement in form validation is to ensure that the user enters a number within a specific range, or allows for no input at all. In this post, we will explore how to implement a Vuetify validation rule for numbers between 0 and 999 or no input. We'll provide code and an example to demonstrate this validation in action.

Profile Photo

Abhishek Yadav (SD) SDE of FAI

Feedback

written
Profile Photo

Anil Kumar (Expert) Coding Expert of FAI

Feeback

reviewed
Profile Photo
Nov 03, 2023 06:11 AM Last Updated
updated

How to Validate Numbers Between 0 and 999 or Allow No Input in Vuetify?

In the following code example, we have a Vuetify form with a text field that allows users to input a number between 0 and 999 or leave the field empty. To achieve this, we define a validation rule using the :rules prop of the text field component.

Vuetify Number Range Validation Rule with No Input

Copied to Clipboard
Run

Here is the JavaScript code that complements the HTML form:

This Vue.js component defines the inputValue data property, which represents the user's input, and the numberValidation computed property that defines the validation rule.

Copied to Clipboard

Vuetify Validation Logic:

Within the numberValidation computed property, we define a validation function that checks the user's input. The function first checks if the input is empty, in which case it returns true, indicating the input is valid. If the input is not empty, it uses a regular expression to ensure it is a numeric value with one to three digits, and also checks if the value falls within the range of 0 to 999. If any of these conditions are not met, an error message is returned, prompting the user to "Enter a number between 0 and 999."

Output of Vuetify Number Range Validation Rule with No Input

Pasted Image

Conclusion

In this post, we've explored how to implement a Vuetify validation rule for numbers between 0 and 999 or allowing no input at all. The key to this validation is the use of computed properties that define custom validation functions. By combining Vue.js and Vuetify, you can easily create forms with complex validation rules to ensure data integrity and user-friendly interactions.

Ad