Phone# Validation with CSS

:valid and :invalid I wish I could add the checkmark ::after the input[type="tel"], but I can't because <input> has no document tree content...

by girlie_mac

HTML

<!-- Phone# Validation with CSS by @girlie_mac 

     You can have a better RegEx if you want. 
     This is just an easy example!
-->

<label for="phone">Enter a 10-digit Phone Number:</label>
<input type="tel" id="phone" value="" 
    placeholder="4153335555" 
    pattern="\d{10}"
    required
/>

<button id="formatBtn" disabled>Format</button>
    
<div id="field"></div>

CSS

/* When the pattern is matched */
input[type="tel"]:valid {
    color: green;
}

input[type="tel"]:valid ~ button::before {
    content: " ✓ ";
    color: green;
}

/* Unmatched */
input[type="tel"]:invalid {
    color: red;
}
  

/* Some UI stuff */
label, input, button, #field {
    font-size: 1.5em;
    padding: .3em;
    border-radius: 1em;
    margin: .2em;
} 
label {
    display: block;
}

JavaScript

var i = document.getElementById("phone"),
    b = document.getElementById("formatBtn"),
    f = document.getElementById("field"),
    regex = i.pattern; // grab the pattern from the attribute!

// if the user input matches the pattern, enable the button
i.addEventListener("input", function(e){
    b.disabled = true;  
    var n = i.value;  
    if (n.match(regex)) {
        b.disabled = false;
    }
}, false);

// some action - this example just formats the number
b.addEventListener("click", function(e){
    f.innerHTML = "";
    var n = i.value;
    var newN = "(" + n.substring(0,3) + ") " + n.substring(3,6) + "-" + n.substring(6,10);   
    f.innerHTML = newN;
}, false);