Shake on Invalid Input

CSSCSSBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will explore CSS animations and pseudo-classes to create an input validation effect. Specifically, we will create a shake animation on invalid input using keyframes and the :invalid pseudo-class. This lab will help you improve your CSS skills and learn how to add dynamic and engaging effects to your web pages.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL css(("`CSS`")) -.-> css/BasicConceptsGroup(["`Basic Concepts`"]) css(("`CSS`")) -.-> css/BasicStylingGroup(["`Basic Styling`"]) css(("`CSS`")) -.-> css/CoreLayoutGroup(["`Core Layout`"]) css(("`CSS`")) -.-> css/DynamicStylingGroup(["`Dynamic Styling`"]) css(("`CSS`")) -.-> css/CSSPreprocessorsGroup(["`CSS Preprocessors`"]) css/BasicConceptsGroup -.-> css/selectors("`Selectors`") css/BasicStylingGroup -.-> css/colors("`Colors`") css/CoreLayoutGroup -.-> css/box_model("`Box Model`") css/CoreLayoutGroup -.-> css/margin_and_padding("`Margin and Padding`") css/DynamicStylingGroup -.-> css/animations("`Animations`") css/CSSPreprocessorsGroup -.-> css/mixins("`Mixins`") subgraph Lab Skills css/selectors -.-> lab-35237{{"`Shake on Invalid Input`"}} css/colors -.-> lab-35237{{"`Shake on Invalid Input`"}} css/box_model -.-> lab-35237{{"`Shake on Invalid Input`"}} css/margin_and_padding -.-> lab-35237{{"`Shake on Invalid Input`"}} css/animations -.-> lab-35237{{"`Shake on Invalid Input`"}} css/mixins -.-> lab-35237{{"`Shake on Invalid Input`"}} end

Shake on Invalid Input

index.html and style.css have already been provided in the VM.

To create a shake animation when there is invalid input, follow these steps:

  1. Use the pattern attribute to define a regular expression that specifies the allowed input. For example, use [A-Za-z]* to allow only letters.
  2. Define a shake animation using @keyframes. Set the margin-left property to move the input left and right.
  3. Use the :invalid pseudo-class to apply the shake animation to the input.
  4. Optionally, add a red box-shadow to the input to indicate the error.

Here's an example code snippet:

<input type="text" placeholder="Letters only" pattern="[A-Za-z]*" />
@keyframes shake {
  0% {
    margin-left: 0rem;
  }
  25% {
    margin-left: 0.5rem;
  }
  75% {
    margin-left: -0.5rem;
  }
  100% {
    margin-left: 0rem;
  }
}

input:invalid {
  animation: shake 0.2s ease-in-out 0s 2;
  box-shadow: 0 0 0.6rem #ff0000;
}

Please click on 'Go Live' in the bottom right corner to run the web service on port 8080. Then, you can refresh the Web 8080 Tab to preview the web page.

Summary

Congratulations! You have completed the Shake on Invalid Input lab. You can practice more labs in LabEx to improve your skills.

Other CSS Tutorials you may like