Skip to main content

Regular Expressions: Form Validation

Hands-On Lab

 

Photo of Elle Krout

Elle Krout

Content Team Lead in Content

Length

01:00:00

Difficulty

Intermediate

One common use of regular expressions is for form validation. Using regular expressions, we can check to ensure that password use the correct characters, that email addresses contain domain information, and more. In this learning activity, we'll create various regular expressions to validate a number of fields in a registration form, making sure our front-end users can create accounts.

What are Hands-On Labs?

Hands-On Labs are scenario-based learning environments where learners can practice without consequences. Don't compromise a system or waste money on expensive downloads. Practice real-world skills without the real-world risk, no assembly required.

Regular Expressions: Form Validation

Introduction

One common use of regular expressions is for form validation. Using regular expressions, we can check to ensure that password use the correct characters, that email addresses contain domain information, and more. In this learning activity, we'll create various regular expressions to validate a number of fields in a registration form, making sure our front-end users can create accounts.

Solution

  1. Begin by logging in to the lab server using the credentials provided on the hands-on lab page:

    ssh cloud_user@PUBLIC_IP_ADDRESS
  2. Edit the index.html file:

    vi /var/www/html/index.html
  3. Scroll down to the function validate() section.

Set the regex expression for the name value

  • Define a regular expression for the name_val.

    var name_val = /^(?=S*s)[A-Za-z ]+$/;

Set the regex expression for the email value

  • Define an email_var regular expression.

    var email_val = /^[w[w.-]+@w[w.-]+.[A-Za-z.]{2,63}$/;

Set the regex expression for the username value

  • Define the regular expression for the username_val variable.

    var username_val = /^[w.-]+$/;

Set the regex for the password value

  • Set password_val to an appropriate regular expression.

    var password_val = /^(?=[^a-z]*[a-z])(?=[^A-Z]*[A-Z])(?=D*d)(?=[^!*%.&]*[!*%.&])(.{10,20})$/;

Set the regex for the credit card value

  • Set credit_val to a regular expression to match a credit card.

    var credit_val = /^d{13,16}$/;

Feel free to test the validation steps by navigating to the lab server's public IP address in your browser.

Conclusion

Congratulations — you've completed this hands-on lab!