When using HTML5 form validation, try using a browser to detect invalid views / fields, rather than reinventing the wheel.
Listen for the invalid event to add an invalid form to the form. With the "invalid" class added, you can go to town by creating a form using CSS3 :pseudo selectors.
For example:
// where myformid is the ID of your form var myForm = document.forms.myformid; var checkCustomValidity = function(field, msg) { if('setCustomValidity' in field) { field.setCustomValidity(msg); } else { field.validationMessage = msg; } }; var validateForm = function() { // here, we're testing the field with an ID of 'name' checkCustomValidity(myForm.name, ''); if(myForm.name.value.length < 4) { checkCustomValidity( // alerts fields error message response myForm.name, 'Please enter a valid Full Name, here.' ); } }; /* here, we are handling your question above, by adding an invalid class to the form if it returns invalid. Below, you'll notice our attached listener for a form state of invalid */ var styleInvalidForm = function() { myForm.className = myForm.className += ' invalid'; } myForm.addEventListener('input', validateForm, false); myForm.addEventListener('keyup', validateForm, false); myForm.addEventListener('invalid', styleInvalidForm, true);
Now just draw your form as you see fit, based on the βinvalidβ class that we hooked up.
For example:
form.invalid input:invalid, form.invalid textarea:invalid { background: rgba(255, 0, 0, .05); border-color: #ff6d6d; -webkit-box-shadow: 0 0 6px rgba(255, 0, 0, .35); box-shadow: 0 0 6px rgba(255, 0, 0, .35); }
Jonathan Calvin Oct 26 '13 at 17:56 on 2013-10-26 17:56
source share