Bhardwaz Chetry
Bhardwaz Chetry

Reputation: 31

How to set different color in CSS for focus one for valid and one for invalid

I want two different color if the value is valid and if it is invalid. ym is yearmonth value= yyyymm lot is a number from 1 to 5 if ym value is null, then we can't give value for lot. thats the code about.

function validate() 
{  
   if(document.myform.ym.value.length=="")
   {
     document.myform.ym.focus();
   }
   if(document.myform.ym.value.length!=6)
   {   
     document.myform.ym.focus();
     document.getElementById("lot").value=null;
   }  
}

Upvotes: 1

Views: 218

Answers (2)

Ehsan
Ehsan

Reputation: 12969

Use of pattern='\d{4}[/]\d{2}'

A)

input[type="text"]:valid {
  border: 2px solid green;
} 

input[type="text"]:invalid {
  border: 2px solid red;
} 
<input type='text' pattern='\d{4}[/]\d{2}' placeholder='yyyymm'>

B)

input[type="text"]:valid + span:after{
  content: '\2714';
  color: green;
} 

input[type="text"]:invalid + span:after {
  content: '\2718';
  color: red;
} 
<input type='text' pattern='\d{4}[/]\d{2}' placeholder='yyyymm'> <span></span>

Upvotes: 0

Albzi
Albzi

Reputation: 15619

For invalid and valid styles, it's as simple as :valid and :invalid. You can set up your own pattern to get the styling to understand what is valid and not.

input:valid {
background:green;
}

input:invalid {
background:red;
}
<input type='text' pattern='[0-9]{6}' maxlength='6' placeholder='yyyymm'>

Upvotes: 4

Related Questions