Form input validations using pure CSS

Viewed 630

Is there any way to apply CSS classes based on HTML element's property (not based on element's attribute) without using JavaScript?

For example, consider below input element:

<input type="text" id="txtName" class="form-field__input" name="txtName" value="">

When user interacts with above element and enters some text, its "value" property gets updated; but "value" attribute remains empty. By any means can we access element's property inside CSS ? I know it is possible to update "value" attribute using JavaScript, and then using attribute selectors update the styles; but is there any way to achieve this using CSS selectors only ?

To clarify, I am not concerned about whether the input is valid or not, I just want to check availability of content, and if the content is present then "any-css-rule-1" should get applied, otherwise "any-css-rule-2".

2 Answers

You can achieve it with combination of HTML5 and CSS3 features. Here is my sample code:

HTML:

<form  action="#" class="contact-us-form" onsubmit="submitClick()">
  <input type="text" placeholder="First Name" required>
  <input type="text" placeholder="Last name">
  <input type="email" placeholder="Email" required>
  <input type="submit"/>
</form>
<p id="demo"></p>

SCSS:

.contact-us-form {
  display: flex;
  padding-bottom: 1.25em;
  flex-direction: column;

  .text-field {
    margin: 0.5em;
  }
  .button-submit {
    margin: 1em;
    width: 100px;
    float: right;
  }

  input[type="text"],
  input[type="email"] {
    margin: 0.5em;
    height: 2em;
    min-width: 125px;
    border: 1px solid #eee;
    border-left: 3px solid;
    border-radius: 4px;
    transition: border-color 0.5s ease-out;

    &:optional {
      border-left-color: #999;
    }
    &:required {
      border-left-color: red;
    }
    &:invalid {
      border-left-color: salmon;
    }
  }
}

JavaScript

function submitClick() {
 alert("Your data has been saved");
}

Here is the link to JSFiddle

Related