Explain Codes LogoExplain Codes Logo

Can I mark a field invalid from JavaScript?

javascript
validation
client-side
server-side
Anton ShumikhinbyAnton Shumikhin·Aug 29, 2024
TLDR

Absolutely! Use JavaScript's setCustomValidity() method on an input element to instantly mark a field as invalid. Set an error message for invalid status or clear it with an empty string to indicate validity.

document.querySelector('#myInput').setCustomValidity('Aim for at least 4 characters');

Now, for dynamic validity based on user action:

let input = document.querySelector('#myInput'); input.oninput = () => input.setCustomValidity(input.value.length >= 4 ? '' : 'Aim for at least 4 characters');

This code will set the input field as invalid when the input length doesn't hit the magic number 4, and valid when it does.

In-depth details

Security: Client-side isn't enough

Client-side JavaScript validation is fantastic but it's like Swiss cheese- full of holes. Always back it up with server-side validation to avoid any sneaky manipulation.

Overriding HTML's default validation

Tired of HTML's built-in validation? Cast your own validation spell with a submit handler:

document.querySelector('form').onsubmit = function(event) { if (!validateMyForm()) { // "Hello Server? Are we good to go?" event.preventDefault(); } };

In the above code, validateMyForm() performs your validation magic and returns true or false to control form submission.

Visual feedback for invalid fields

Lights, CSS, Action! Give your users visual cues for invalid fields. Add or remove CSS classes or styles based on the input validity:

input.oninput = () => { let msg = input.value.length >= 4 ? '' : 'Aim for at least 4 characters'; // "Four shall be the number thou shalt count... " input.setCustomValidity(msg); input.className = input.validity.valid ? 'valid' : 'invalid'; // Red pill, blue pill. Your choice, Neo. };

The above will toggle the input's class between valid and invalid, letting you style away to your heart's content.

Regex: Perfect for pattern matching

Regex, the voodoo doll of JavaScript, is perfect for complex validation like email or custom formats. Stringuem Leviosa and you can match against complex patterns and formats.

Streamlining user inputs

KISS- "Keep it simple, Sam". Only validate crucial information you need from users. A friendly user interface takes minimum yet sufficient input, balancing between security and usability.

In the realm of jQuery

In the jQuery territory, use the jQuery $ to directly apply validation to your fields:

let $input = $('#myInput'); $input.on('input', () => { $input[0].setCustomValidity($input.val().length >= 4 ? '' : 'Aim for at least 4 characters'); }); // Disabling HTML5 form validation. Sorry HTML, we don't need you here! $('form').attr('novalidate', 'novalidate');

Broaden your validation scope

Cross-browser support in one word? Plugins. Libraries like jq-idealforms provide blanket solutions for validation across a plethora of browsers and devices.

Visual marks of validation

When you mark a field as invalid, it's like red inking an error on a document:

[ ✅ ] <- This is your input field in a 'valid' state!

Give this power to your JavaScript:

document.querySelector('input').setCustomValidity('Invalid Input');

The field is then marked with the red ink of invalidity:

[ ❌ ] <- Now the field is in an 'invalid' state!

The validation message can be likened to the crucial footnote explaining the red mark.