html input validation :valid :invalid - html

I've created an input control with validation:
required
minlength = 4
maxlength = 8
The input's initial value set to 'ab'.
Since the 'ab' doesn't satisfy the validation, the :invalid selector should work.
But at the first load (unedited by user), the :invalid doesn't work.
Is there any way to force validation in all time?
<input type='text' id='test' value='ab' required minlength=4 maxlength=8 />
#test:valid {
background: lightGreen;
}
#test:invalid {
background: pink;
}

Looks like it's always saying it's valid.
Have you tried putting ""'s around the 4 and 8 values?
Like so:
minlength="4"
maxlength="8"
Can you post more of your code?

Related

How can I restrict a time input value?

I want to display an input type hour from 08:00 to 20:00. I tried this:
<input type="time" id="timeAppointment" name = "timeAppointment" min="08:00" max="20:00" placeholder="hour" required/>
But when I display it I can still select any time, it does not restrict me as I indicate. What is the problem? If is necessary some code I work with Javascript.
The constraints within the input do not prevent from entering an incorrect value in this case. Here is an overview of what MDN says in their documentation:
By default, does not apply any validation to entered values, other than the user agent's interface generally not allowing you to enter anything other than a time value.
But you can write validations with JavaScript, or visual validations with CSS, like so:
.container{
display:flex;
align-items:center;
gap:1rem;
}
input:invalid+span:after {
content: '✖';
}
input:valid+span:after {
content: '✓';
}
<div class = "container">
<input type="time" id="timeAppointment" name = "timeAppointment" value="08:00" min="08:00" max="20:00" placeholder="hour" required/>
<span class="validity"></span>
</div>
Setting min and max properties in input tags do not inherently prevent you from accepting out of range values as inputs, but it controls the valid property of the tag, which can then be used such as in css to style your page accordingly. Some browsers do make it so that you cannot input out of the specified range, but it is not platform-independent behaviour.
See more here: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/time#setting_maximum_and_minimum_times
If you want to ensure that only the time between min and max are input, you could programmatically implement that using an onchange listener on your input element as follows:
Make sure to indicate to the user why their input is not changing (because it is not between min and max) using css and text, etc.
const timeInput = document.getElementById("timeAppointment");
timeInput.value = '15:56';
let previousValue = timeInput.value;
timeInput.onchange = () => {
console.log(previousValue)
console.log(timeInput.value)
if (timeInput.value < timeInput.min || timeInput.value > timeInput.max) {
timeInput.value = previousValue;
}
previousValue = timeInput.value;
}
<input type="time" id="timeAppointment" name="timeAppointment" min="08:00" max="20:00" required/>
However, there is a caveat to this. Imagine you are changing your time from 02:00PM to 11:00AM. You would go from left to right, and as soon as you change 02 hours to 11 hours, the javascript validation fails as it becomes 11:00PM and the value is not able to update.
Either you will have to write a convoluted way to get around all the edge cases, or the users will have to find a weird way to change their time. This is why this is generally a bad idea to validate on every input like this, and instead you can validate it when you submit the form, or onfocusout and let the user know by appropriate styling.

css input text name value color [duplicate]

Is it possible to use a CSS selector to target an input that has a specific value?
Example: How can I target the input below based on the value="United States"
<input type="text" value="United States" />
Dynamic Values (oh no! D;)
As npup explains in his answer, a simple css rule will only target the attribute value which means that this doesn't cover the actual value of the html node.
JAVASCRIPT TO THE RESCUE!
Ugly workaround: http://jsfiddle.net/QmvHL/
Original Answer
Yes it's very possible, using css attribute selectors you can reference input's by their value in this sort of fashion:
input[value="United States"] { color: #F90; }​
• jsFiddle example
from the reference
[att] Match when the element sets the "att" attribute, whatever the
value of the attribute.
[att=val] Match when the element's "att"
attribute value is exactly "val".
[att~=val] Represents an element
with the att attribute whose value is a white space-separated list of
words, one of which is exactly "val". If "val" contains white space,
it will never represent anything (since the words are separated by
spaces). If "val" is the empty string, it will never represent
anything either.
[att|=val] Represents an element with the att
attribute, its value either being exactly "val" or beginning with
"val" immediately followed by "-" (U+002D). This is primarily intended
to allow language subcode matches (e.g., the hreflang attribute on the
a element in HTML) as described in BCP 47 ([BCP47]) or its successor.
For lang (or xml:lang) language subcode matching, please see the :lang
pseudo-class.
css attribute selectors reference
It is possible, if you're using a browser which supports the CSS :valid pseudo-class and the pattern validation attribute on inputs -- which includes most modern browsers except IE9.
For instance, to change the text of an input from black to green when the correct answer is entered:
input {
color: black;
}
input:valid {
color: green;
}
<p>Which country has fifty states?</p>
<input type="text" pattern="^United States$">
Yes, but note: since the attribute selector (of course) targets the element's attribute, not the DOM node's value property (elem.value), it will not update while the form field is being updated.
Otherwise (with some trickery) I think it could have been used to make a CSS-only substitute for the "placeholder" attribute/functionality. Maybe that's what the OP was after? :)
As mentioned before, you need more than a css selector because it doesn't access the stored value of the node, so javascript is definitely needed. Heres another possible solution:
<style>
input:not([value=""]){
border:2px solid red;
}
</style>
<input type="text" onkeyup="this.setAttribute('value', this.value);"/>
Sure, try:
input[value="United States"]{ color: red; }
jsFiddle example.
You can use Css3 attribute selector or attribute value selector.
/This will make all input whose value is defined to red/
input[value]{
color:red;
}
/This will make conditional selection depending on input value/
input[value="United States"]{
color:red;
}
There are other attribute selector like attribute contains value selector,
input[value="United S"]{
color: red;
}
This will still make any input with United state as red text.
Than we attribute value starts with selector
input[value^='united']{
color: red;
}
Any input text starts with 'united' will have font color red
And the last one is attribute value ends with selector
input[value$='States']{
color:red;
}
Any input value ends with 'States' will have font color red
Refreshing attribute on events is a better approach than scanning value every tenth of a second...
http://jsfiddle.net/yqdcsqzz/3/
inputElement.onchange = function()
{
this.setAttribute('value', this.value);
};
inputElement.onkeyup = function()
{
this.setAttribute('value', this.value);
};
In Chrome 72 (2019-02-09) I've discovered that the :in-range attribute is applied to empty date inputs, for some reason!
So this works for me: (I added the :not([max]):not([min]) selectors to avoid breaking date inputs that do have a range applied to them:
input[type=date]:not([max]):not([min]):in-range {
color: blue;
}
Screenshot:
Here's a runnable sample:
window.addEventListener( 'DOMContentLoaded', onLoad );
function onLoad() {
document.getElementById( 'date4' ).value = "2019-02-09";
document.getElementById( 'date5' ).value = null;
}
label {
display: block;
margin: 1em;
}
input[type=date]:not([max]):not([min]):in-range {
color: blue;
}
<label>
<input type="date" id="date1" />
Without HTML value=""
</label>
<label>
<input type="date" id="date2" value="2019-02-09" />
With HTML value=""
</label>
<label>
<input type="date" id="date3" />
Without HTML value="" but modified by user
</label>
<label>
<input type="date" id="date4" />
Without HTML value="" but set by script
</label>
<label>
<input type="date" id="date5" value="2019-02-09" />
With HTML value="" but cleared by script
</label>
Following the currently top voted answer, I've found using a dataset / data attribute works well.
//Javascript
const input1 = document.querySelector("#input1");
input1.value = "0.00";
input1.dataset.value = input1.value;
//dataset.value will set "data-value" on the input1 HTML element
//and will be used by CSS targetting the dataset attribute
document.querySelectorAll("input").forEach((input) => {
input.addEventListener("input", function() {
this.dataset.value = this.value;
console.log(this);
})
})
/*CSS*/
input[data-value="0.00"] {
color: red;
}
<!--HTML-->
<div>
<p>Input1 is programmatically set by JavaScript:</p>
<label for="input1">Input 1:</label>
<input id="input1" value="undefined" data-value="undefined">
</div>
<br>
<div>
<p>Try typing 0.00 inside input2:</p>
<label for="input2">Input 2:</label>
<input id="input2" value="undefined" data-value="undefined">
</div>

Add Background color after setting content in input field

Is there any way that i could add a background color after placing a content inside an input field? Just like what happens when an autocomplete works.
Thanks!
There are a few ways you could achieve this. You could make the input mandatory by adding the required attribute. Doing this means that as soon as the user enters anything into the field, it is now in the valid state and you can target it in your CSS using the :valid pseudo-class:
input:valid{
background:#ff9;
}
<input required>
Or, if you don't want to make the field mandatory and as others have suggested, you could set the new background-color when the field receives focus. To prevent it from reverting to its initial color when it loses focus, you will need to add a transition to the background, setting the transition-delay to some ridiculously high number when the input is in its normal state and resetting it to 0s when it is focused. Obviously, though, this change will occur whether or not the user actually enters anything in the field or not.
input{
transition-delay:9999s;
transition-property:background;
}
input:focus{
background:#ff9;
transition-delay:0s;
}
<input>
If neither of those options suit your needs then you will probably need to resort to using JavaScript to add or remove a class, depending on whether or not the value of the input is empty.
document.querySelector("input").addEventListener("input",function(){
this.value?this.classList.add("filled"):this.classList.remove("filled");
},0);
.filled{
background:#ff9;
}
<input>
Html
First name: <input type="text" name="firstname">
Css
input:focus {
background-color: yellow;
}
Demo in JsFiddle
Here is a solution with pure javascript
var input = document.getElementById("test");
input.addEventListener('input', function() {
if (input.value)
input.style.backgroundColor = '#90EE90';
else
input.style.backgroundColor = '#fff';
});
<input id="test" type="text" value="">
Add a Css class like
.myCSSClass
{
background-color:red;
}
Now using jquery on blur function you add this class
$("#myTextBox").on('blur',function(){
if($("#myTextBox").val()==""){
if($("#myTextBox").hasClass("myCSSClass")){
$("#myTextBox").removeClass("myCSSClass");
}
}
else
{
$("#myTextBox").addClass("myCSSClass")
}
});
Using Jquery,
$( "#target" ).blur(function() {
$( "#target" ).css('background-color','red');
});
DEMO

How do I duplicate 'input required' functionality without sending with the form?

I would like to have the built-in functionality of having a text input (in the middle of other text inputs) be checked and flagged (i.e. the default red marquee applied around the text box) to make sure it is populated before the user clicks the form submit button, without including that value in the form submission. Basically, I don't want to send the retyped password with the form, but it of course needs to be filled in (and will be checked client-side). Is there a "simple" way to do this?
Here is a very minimal example of what you want.
You can do this type of logic using JavaScript events like onblur, onfocus, onchange, etc.
Here is an example showing you how you can validate that a field has a value in it.
var validate = function(element) {
// element is HTMLInputElement
if (element.value == "") {
element.className = "border-red";
} else {
element.className = "";
}
}
.red {
color: red;
}
.border-red {
border: 2px solid red;
}
<form>
Required: <input type="text" name="required_field" onblur="validate(this)" />
Optional: <input type="text" name="optional" />
</form>

Is there a CSS not equals selector?

Is there something like != (not equal) in CSS?
e.g, I have the following code:
input {
...
...
}
but for some inputs I need to void this. I'd like to do that by adding the class "reset" to the input tag, e.g.
<input class="reset" ... />
and then simply skip this tag from CSS.
How I can do that?
The only way I can see would be to add some class to the input tag, and rewrite the CSS as follows:
input.mod {
...
...
}
In CSS3, you can use the :not() filter, but not all browsers fully support CSS3 yet, so be sure you know what you're doing which is now
supported by all major browsers (and has been for quite some time; this is an old answer...).
Example:
<input type="text" value="will be matched" />
<input type="text" value="will not be matched" class="avoidme" />
<input type="text" value="will be matched" />
and the CSS
input:not(.avoidme) { background-color: green; }
Note: this workaround shouldn't be necessary any more; I'm leaving it here for context.
If you don't want to use CSS3, you can set the style on all elements, and then reset it with a class.
input { background-color: green; }
input.avoidme { background-color: white; }
You can also do that by 'reverting' the changes on the reset class only in CSS.
INPUT {
padding: 0px;
}
INPUT.reset {
padding: 4px;
}
You could also approach this by targeting an attribute like this:
input:not([type=checkbox]){
width:100%;
}
In this case all inputs that are not 'checkbox' type will have a width of 100%.
CSS3 has :not(), but it's not implemented in all browsers yet. It is implemented in the IE9 Platform Preview, however.
input:not(.reset) { }
http://www.w3.org/TR/css3-selectors/#negation
In the meantime, you'll have to stick to the old-fashioned methods.
Interesting just tried this for selecting DOM element using JQuery and it works! :)
$("input[class!='bad_class']");
This page has 168 divs which does not have class 'comment-copy'
$("div[class!='comment-copy']").length => 168
$("div[class!='.comment-copy']").length => 168
instead of class="reset" you could reverse the logic by having class="valid"
You can add this by default and remove the class to reset the style.
So from your example and Tomas'
input.valid {
...
...
}
and
<input type="text" value="will be matched" class="valid"/>
<input type="text" value="will not be matched" />
<input type="text" value="will be matched" class="valid"/>