Pyinquirer not validating integer values

1.4k views Asked by At

I´m using Py inquirer @ latest version. Python version is 3. I setup a test Programm. Just the basics and copy paste this from the project docu

import inquirer
questions = [
  inquirer.Text('name', message="What's your name"),
  inquirer.Text('surname', message="What's your surname"),
  inquirer.Text('phone', message="What's your phone number",
                validate=lambda _, x: re.match('\+?\d[\d ]+\d', x),
                )
]
answers = inquirer.prompt(questions)

The first and second question working, the third one, with the validation not. There is completely no matter of the input, I always get the following error:

"220" is not a valid phone. 

I googled a lot (maybe the wrong keywords), I tried to change the regex, but nothing helps.

Can someone help me ?

1

There are 1 answers

0
Dricom On

I had a problem with PyInquirer validation : sometimes input were validated despite the format was not as expected. So the issue was different, but maybe the cause is similar.

Try to change your regex from \+?\d[\d ]+\d to ^\+?\d[\d ]+\d$. This will match the beginning and the end of the expression.

I hope it would help (I didn't test it for inquirer)

Here the code I tested with PyInquirer, just in case :

from PyInquirer import prompt, Validator, ValidationError
from prompt_toolkit import document
import regex

class PhoneValidator(Validator):
    def validate(self, document: document.Document) -> None:
        ok = regex.match('^\+?\d[\d ]+\d$', document.text)
        if not ok:
            raise ValidationError(message = 'Please enter a valid phone number', cursor_position = len(document.text))

widget = [
    {
        'type':'input',
        'name':'number',
        'message':'Type your phone number',
        'validate':PhoneValidator
    }
]

try :
    result = prompt(widget)
except ValueError :
    print('Pb !!!')
    exit()

print('Your answer is')
print(result["number"])
print(type(result["number"]))