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

Surjya Narayana Padhi picture Surjya Narayana Padhi · Mar 6, 2011 · Viewed 11.6k times · Source

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?

Answer

serge_gubenko picture serge_gubenko · Mar 6, 2011

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