Validate input type number with range min/max

Hello, sorry for the newbie question, I’m exploring Vue.js and trying to use it in a research project.

In my app I create dynamically rows in a table.

Inside every row, I have 6 cells and in one cell I have an input field:

<input type="number" min=1 max=5 id="myID" name="myName" v-model:userChoice>

Most browsers “ignore” (it’s their default behavior) min and max, so that the user can freely edit the input field and type a number that’s not in the range 1-5.

When the user has ended adding rows, I retrieve data related to the rows I stored in a rows array. Problem is data coming from the input could be invalid (eg. 0 or 6).

I would like to correct wrong values “live”: that is, if a user sets 0, I want that particular field filled with a red background (it’s just an example) and remove this background when the value is in the range. Is it possible?

(sub-question: is it possible to get a reference to a particular field when any field created dynamically has the same id?)

Thanks in advance :slight_smile:

If it’s just a one time thing, you could do :class="{invalid:userChoice < 1 || userChoice > 5}".

On a bigger project with many forms you might want to use a package like vuelidate.

2 Likes

Ok, thanks. And I have a button to send data: is there any way to disable it when the values of any of the inputs in the rows are out of range and enable it again when userChoice >=1 && <=5?

Sure, like this:
:disabled="rows.find(row => row.userChoice < 1 || row.userChoice > 5)"

2 Likes

I must say I really like Vue :slight_smile:

i had same issue and i made this:

@input="checkValue(economicValue, ‘economicValue’, [0, 999999])

checkValue(value, field, range){
if(value < range[0]){
return this[field] = range[0];
}else if(value > range[1]){
return this[field] = range[1];
}
},

You can makeup to use onChange event handler.

example code

<input type="number" v-model="cnt" @change="() => { if(cnt > 5 || cnt < 0) { this.cnt = 0 }}">