preg_match conditions required

Hello everyone,

I am a bit week with regular expressions in PHP, in any language actually. I am building a registration form and I am checking for certain conditions. I have solved a few of them, but I got stuck with these.

I do not want the user to be registered if:

  1. The username can be only alphanumeric but must start with an alphabet. No special characters to be allowed.
  2. The first name and last name can have only alphabets and not anything else.
  3. The roll number can only be a 10 digit number, not anything less, not anything more, no other characters allowed.
  4. The most important of all, I want users to sign up with email id given by my college. That is, allow registrations only if specific domain exists in the email ID.

Can anyone please help me with these, and also explain the codes?

Thank You

// this forces username to be at least 2 chars long and at most 30 chars:
// 1 letter plus 1 to 29 alphanumeric chars.
// ^ means start of the string
// $ means end of the string
// i means case insensitive
if (!preg_match('/^[a-z][0-9a-z]{1,29}$/i', $username)) {
  // wrong username!
  // ...

// this forces firstname to be between 2 and 30 chars, only letters
if (!preg_match('/^[a-z]{2,30}$/i', $firstname)) {
  // wrong firstname!
  // ...

if (!preg_match('/^[0-9]{10}$/', $rollnumber)) {
  // wrong roll number!
  // ...

// . has a special meaning in regex so we need to escape it with \\
// note that this will not fully validate the email, this will only check if it
// ends with the right domain
if (!preg_match('/@mycollegedomain\\.edu$/i', $email)) {
  // wrong domain in email!
  // ...

You beauty Lemon Juice. Thanks a lot, everything worked like a charm :slight_smile: And your explanations were very good. However, I have one doubt. ‘i’ is for insensitive you said. Then shouldn’t all the email id’s be made lower case?

Domain names are case-insensitive that’s why I included ‘i’. The part before @ can theoretically be case sensitive but in practice I haven’t heard of an ISP that enforces that. That’s why I wouldn’t require lower case on emails :).