Reputation: 3836
I'm using vue-tags-input component. In its docs we can find validation. I'm trying to create validation so valid input must have:
this is what I have:
validation: [{
classes: 'min-length',
rule: tag => tag.text.length < 3,
},{
classes: 'min-length',
rule: ({ text }) => {
const comma = text.indexOf(',') === -1;
if(comma) {
const arr = text.split(',')
if(arr[0] && arr[1]) {
if(arr[0].typeof === 'number' && arr[1].typeof === 'number') {
return true;
}
}
}
return false;
}
}]
So I'm spliting string to array by ,
. In result I should have array with two elements. Then I check if both elemenets are numbers. How ever this not work properly because it treat 111
as valid but it shoudn't.
I've created demo on codesanbox.
Upvotes: 0
Views: 668
Reputation: 17546
To check if comma exists you have to check if indexOf
comma not equals -1.
const comma = text.indexOf(",") !== -1;
You have to convert the string to number using Number(string)
.
if (typeof Number(arr[0]) === "number") {..
You have to return false if validation succeeds and true if there is an error, you are doing the opposite.
The complete code will be:
{
classes: "custom",
rule: ({ text }) => {
const comma = text.indexOf(",") !== -1;
if (comma) {
const arr = text.split(",");
if (arr[0] && arr[1]) {
if (typeof Number(arr[0]) === "number" && typeof Number(arr[1]) === "number") {
return false;
}
}
}
return true;
}
}
A shorter regex rule will be:
{
classes: "custom",
rule: ({ text }) => {
return !text.match(/^\d+,\d+$/);
}
}
Upvotes: 1