Basic validation
Learn basic validation with required fields and length checks.
Required field check
To check that a field was not left empty, you clean it with trim and compare it to the empty string. This is the most basic validation step.
const name = input.value.trim();
if (name === '') {
console.log('Name required');
}Fields filled with only spaces are caught by this check. Showing the error to the user with visual feedback comes in later lessons.
Length check
To ask for a longer value, you use the length property. The string's length comes back as a number and is checked with comparison operators.
const value = input.value.trim();
if (value.length < 3) {
console.log('At least 3 characters');
}>= means 'at least', > means 'more', <= means 'at most', < means 'less'. Keep the validation message short and clear.
Exercise Validate the name field
The nameInput variable points to an input field. Clean its value with trim. If empty, log 'Name required'; if shorter than 3 characters, log 'At least 3 characters'; otherwise log 'OK'.
Show example solution
const name = nameInput.value.trim();
if (name === '') {
console.log('Name required');
} else if (name.length < 3) {
console.log('At least 3 characters');
} else {
console.log('OK');
}
Test yourself
-
Match validation patterns
- value.trim() === ''
- Empty field check
- value.length >= 3
- At least 3 characters
- value.length < 3
- Too short value
-
Which correctly applies 'at least 3 characters'?
const value = input.value.trim(); // A if (value.length >= 3) { console.log('OK'); } // B if (value.length = 3) { console.log('OK'); } // C if (value.length > 3) { console.log('OK'); } // D if (value = 3) { console.log('OK'); }- A
- B
- C
- D
Show answer
A — Correct! >= 3 means '3 or more'; it also accepts exactly 3 characters.
-
Complete the length check
const value = input.value.trim(); if (3 > value.____) { console.log('Too short'); }Show answer
const value = input.value.trim(); if (3 > value.length) { console.log('Too short'); }