Chapter 14 · Beyond the DOM
Checking forms
People make typing mistakes: an email without the @, a password that's too short, a box they forgot to tick. In this chapter you'll check a form before it's sent, with rules written as short phrases, and show a clear message under each field that needs fixing.
Why check a form?
Checking a form in the browser means people find their mistakes straight away, next to the field, instead of after waiting for the server. It's faster and kinder.
Checks in the browser are for convenience, not security. Anyone can turn off JavaScript or send data without your page. Always check again on the server, as you saw with PHP in Using Nyx in WordPress.
Your first check: nyx.check
Give nyx.check() the form and a rule for each field, by the field's name. Then .submit() says what to do once everything is right:
nyx.check(check
"#join",this form
{ email: "required, email" }with these rules
).submit(...)then, if all is well
Press Join with the fields as they are, then fix them one by one:
Here's what happens, without any extra code:
- While typingNothing nags. People can type in peace.
- On leaving a fieldThat field is checked, and its message appears underneath.
- While fixing itThe message updates with every key and disappears as soon as the field is right.
- On pressing JoinEvery field is checked, and the cursor jumps to the first one with a problem.
- When everything passesYour
.submit()function runs withdata: all the fields in one object, like.formData()from Servers and AJAX.
The page doesn't reload when the form is sent: Nyx stops that for you, so you don't need event.preventDefault().
Writing rules
- The left side is the field's
name, the same as in<input name="email">. Not itsid. - The right side is a list of rules, in quotes, separated by commas:
"required, min 8, has number". - Rules are checked in order, and only the first problem is shown, so people fix one thing at a time.
- Messages use the field's label: a field labelled "Your name" gets "Your name is required." If there's no
<label>, Nyx usesaria-label, then the placeholder, then the name. - Empty fields are only checked by "required". Leave "required" out, and the field is optional: empty is fine, but if something is typed, the other rules apply.
Spell a rule or a field name wrong, like "requird" or emial:, and Nyx tells you what you probably meant.
Every rule
requiredNot be empty. For a checkbox: be ticked. For radio buttons and menus: have something chosen.emailLook like an email address: name@example.com.phoneLook like a phone number: digits, with spaces, dashes, brackets or a + at the start allowed.urlBe a web address starting with http:// or https://.numberBe a number. Decimals are fine: 12.5.whole numberBe a number without decimals: 12.lettersHave only letters and spaces (and . ' -), for names. Letters from any language count.min 8Have at least 8 characters.max 20Have at most 20 characters.at least 18Be a number of 18 or more.at most 99Be a number of 99 or less.has numberContain at least one digit.has uppercaseContain at least one capital letter.has lowercaseContain at least one small letter.has symbolContain at least one symbol, like ! or @.same as passwordMatch another field exactly, by that field's name.min / max
username: "min 3, max 15"Count the characters: "Asha" has 4.
at least / at most
age: "number, at least 5, at most 18"Compare the number's value: 15 is between 5 and 18.
Passwords and "same as"
A classic sign-up pair: a strong password, and the same password again. Type a password, then a different one in the second box, then fix it:
Change the first password after filling in both, and the second field is checked again too, because it depends on the first.
Checkboxes, radio buttons and menus
"required" knows what filled in means for each kind of field, and words its message to match. Press Register straight away to see all three messages:
name, and put them in a <fieldset>. Its <legend> names the group in messages: "Choose an option for Your class."<option value="">Choose a day</option>. Its empty value means "nothing chosen yet".<label>. The message quotes the label: Tick "I'll attend every week" to continue.Where the messages go
Nyx puts each message in a <small class="nyx-error"> right after its field (or after the field's label, for a checkbox, or at the end of the <fieldset>, for radio buttons). It also marks the field, so the page works for everyone:
class="nyx-error"On the message, so you can style it.aria-invalid="true"On a field with a problem. Screen readers say "invalid", and you can style it.aria-describedbyLinks the field to its message, so screen readers read the message when the field is focused.Messages are red and small by default. Your own CSS always wins, so you can restyle them:
.nyx-error {
color: #b3261e;
font-weight: 600;
}
input[aria-invalid="true"] {
border-color: #b3261e;
background: #fff5f5;
}Nyx also turns off the browser's own pop-up messages for this form, so the two don't compete. Keep type="email" and type="number" on your inputs anyway: phones show the right keyboard for them.
Your own rules: nyx.rule
When the built-in rules aren't enough, make your own with nyx.rule(). Give it a name and a function. The function gets the field's value and returns true if it's fine, or a message if not. {field} in the message becomes the field's label:
nyx.rule("no spaces", ...)Make a rule called "no spaces". Once made, use it in anynyx.check()on the page, like the built-in ones.!value.includes(" ") || "..."If the value has no space, that'strue: fine. Otherwise,||gives the message.value.toLowerCase()Turn it into small letters before comparing, so "Asha" counts as taken too.
Try "my name", then "Asha", then "nyx_fan". Make your rules before nyx.check() uses them.
When the server says no
Some problems only the server can know, like an email that's already registered. Keep what nyx.check() gives back in a variable, and use .showError() to put a message under the right field. Give it the error from catch, and it shows the server's own words, like "This email is already registered." (or give it any text of your own). The message disappears as soon as the person types in that field again.
This uses the practice server from Servers and AJAX, where asha@school.in is already taken. Press Sign up, then try another email:
Checking without sending: .ok()
.ok() checks every field right now, shows the messages, and gives true if everything passes. It's useful for a "Next" button in a form with several steps, where nothing is sent yet:
.ok(false) checks without moving the cursor to the first problem.
Putting it together
A full registration form for a coding club: rules for every field, a custom rule, the server's answer, and a busy button while it's sent:
phone: "phone"No "required", so the phone number is optional, but if it's typed it must look right."whole number, at least 10, at most 18"Only ages from 10 to 18, without decimals..busy(nyx.post(...))The button shows "Loading…" while the server answers, from Servers and AJAX.club.showError("email", error)If the server says the email is taken, show its message under the email field.
Try asha@school.in to see the server's answer, and password1 to see the custom rule.
Common mistakes
name: <input id="e" name="email"> needs email:.name can't be checked or sent. Add one.<label for="...">.name, or each button is its own field.min 18 for an agemin counts characters. For a number's value, use at least 18.nyx.rule() before the nyx.check() that uses it.Exercise
Fill in the blanks, then press Check answers.
1. Check the form #contact.
nyx.("#contact", { email: "required, email" });
2. The message can't be empty.
message: ""
3. A username of at most 15 characters.
username: "required, "
4. An age of 13 or more.
age: "required, number, "
5. The second password must match the field named password.
again: "required, "
6. Make your own rule.
nyx.("no spaces", (value) => !value.includes(" ") || "{field} can't have spaces.");
7. Show the server's message under the email field.
signup.("email", error);
Remember
nyx.check(form, rules).submit(fn): fn runs only when every rule passes, with the form's data.name, separated by commas, and checked in order.min/max count characters; at least/at most compare numbers.nyx.rule() makes your own rules. .showError() shows the server's message. .ok() checks without sending.