JSFiddle - React, Tailwind, and code Playground
HTML
<label for="surname">Surname:<span class="asterx">*</span></label>
<div>
<input type="text" id="surname" name="surname" required placeholder="Please enter your Surname" pattern="[A-Za-z]{2,15}" />
<div class="error" id="e_surname"></div>
</div>
<label for="tel">Phone number:<span class="asterx">*</span></label>
<div>
<input type="tel" id="tel" name="tel" required placeholder="Please enter your Phone number" pattern="[0-9]{9}" />
<div class="error" id="e_tel"></div>
</div>
CSS
label > div {
padding-bottom: 15px;
}
//color
.c-r{
color: red;
}
.c-g{
color: green;
}
//border
.b-r{
border-color: red;
}
.input-red{
background-color: rgb(204, 59, 59);
}
.error{
color: red;
font-size: smaller;
}
JavaScript
const inputs = document.querySelectorAll("input");
inputs.forEach(function(input){
const e_space = document.getElementById("e_" + input.id);;
input.addEventListener("focus", function () {
if(input.classList.contains("input-red")){
input.classList.remove("input-red")
}
})
input.addEventListener("blur", function (){
if(input.type["text"]){
if(input.validity.patternMismatch){
if(e_space){
e_space.textContent = "This field can only contain letters from a-z.";
input.classList.add("b-r");
}
input.classList.add("input-red");
}
}
if(input.type["tel"]){
if(input.validity.patternMismatch){
if(e_space){
e_space.textContent = "This field must contain nine numbers.";
input.classList.add("b-r");
}
input.classList.add("input-red");
}
}
input.value = input.value.trim();
if(input.validity.valueMissing){
if(e_space){
e_space.textContent = "This field must not be empty.";
input.classList.add("b-r");
}
input.classList.add("input-red");
}
if (input.validity.valueMissing === false && input.validity.patternMismatch === false) {
e_space.textContent = "";
input.classList.remove("b-r");
}
})
})