0

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:

  • min 3 signs
  • two numbers
  • comma between numbers

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.

2
  • Are the numbers always integers? Are they always positive? Commented Jul 20, 2019 at 17:41
  • If rule returns true does that mean it passes or fails? Commented Jul 21, 2019 at 14:06

1 Answer 1

1
+50
  1. To check if comma exists you have to check if indexOf comma not equals -1.

    const comma = text.indexOf(",") !== -1;
    
  2. You have to convert the string to number using Number(string).

    if (typeof Number(arr[0]) === "number") {..
    
  3. 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+$/);
  }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.