<main>
	<p>Type in a valid/invalid e-mail address and blur the field</p>

	<!-- Hack: Set a placeholder with a value of " " so that we can hook our CSS onto it using :placeholder-shown -->
	<input type="email" placeholder=" " required />
	
	<p class="error-message">Please enter a valid e-mail address</p>

	<p>💡 The input will show a red/green validation border, but only when the input does not have the focus and is not empty. To achieve the latter we abuse <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/:placeholder-shown" target="_top">the <code>:placeholder-shown</code> pseudo-class selector</a>.</p>
	<p><small><em>Demo 4/4 for <a href="https://brm.us/form-validation-invalid" target="_top">https://brm.us/form-validation-invalid</a></em></small></p>
</main>
:root {
	--color-default: grey;
	--color-invalid: red;
	--color-valid: green;
}

input {
	border: 2px solid var(--color-default);
	text-align: center;
}

.error-message {
	display: none;
	font-weight: bold;
	color: var(--color-invalid);
}

/* To demonstrate that the validations only happen on blur, we apply this malpractice */
input:focus {
	outline: none;
}

/* Only show invalid ring while not focused */
input:not(:focus):not(:placeholder-shown):invalid {
	border-color: var(--color-invalid);
}
input:not(:focus):not(:placeholder-shown):invalid ~ .error-message {
	display: block;	
}

/* Only show valid ring while not focused and if a value is entered */
/* :empty won't work here as that targets elements that have no childeren. Therefore we abuse :placeholder-shown */
input:not(:focus):not(:placeholder-shown):valid {
	border-color: var(--color-valid);
}






/* Non demo-related styles */
* {
	box-sizing: border-box;
}

body {
	text-align: center;
	max-width: 46em;
	width: 90%;
	height: 100vh;
	margin: 0 auto;
	font-family: -apple-system, BlinkMacSystemFont, avenir next, avenir,
		helvetica neue, helvetica, Ubuntu, roboto, noto, segoe ui, arial, sans-serif;

	display: grid;
	place-items: center;
}

input {
	font-size: 2em;
	display: block;
	width: 100%;
	margin: 2rem auto 3rem;
}
Run Pen

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

This Pen doesn't use any external JavaScript resources.