Search code examples
validationqt4expressionqlineedit

QLineEdit Validation for {[A-Z] [a-z][0-9]} text input


I want to accept a new username from the user in my application. I want the username string to contain only A-Z or a-z or 0-9, and have a maxLength of 8. So I want to validate the input from QLineEdit. I went through the documentation but I am messed up with validators. How I can validate my QLineEdit for this purpose?


Solution

  • You can use setInputMask to specify the validation input mask, in your case you can use "N" or "n' to permit only characters in A-Z, a-z and 0-9 range. something like this:

    lineEdit->setInputMask("nnnnnnnn;_"); // or NNNNNNNN;_
    lineEdit->setCursorPosition(0);
    

    You also can set QValidator instance to your lineEdit, via set setValidator. This sets the lineEdit to only accept input that the validator, will accept. This will work in conjunction with edit masks

    If you only need to restrict the max permitted length of the line edit: use setMaxLength

    lineEdit->setMaxLength(8);
    

    hope this helps, regards