Unit 4: Form Handling and Validation - Practice Quiz

INT252 — Web App Development With Reactjs 60 Questions
0 Correct 0 Wrong 60 Left
0/60

1 In React, what makes a form input a controlled component?

Controlled and uncontrolled components Easy
A. Its value is stored only in the DOM
B. Its value is managed by the browser cache
C. Its value is fixed by CSS rules
D. Its value is managed by React state

2 Which React feature is commonly used to access the current value of an uncontrolled input?

Controlled and uncontrolled components Easy
A. A context provider
B. A reducer function
C. A React ref
D. A memoized value

3 Which React Hook is commonly used to manage a simple form field value?

Form state management patterns Easy
A. useEffect
B. useState
C. useRef
D. useMemo

4 What is a common way to manage several related form fields in one state value?

Form state management patterns Easy
A. Store the fields in a DOM attribute
B. Store the fields in an object
C. Store the fields in a route path
D. Store the fields in a style sheet

5 Which form event is normally handled when a React form is submitted?

Handling form submission workflows Easy
A. onSubmit
B. onMouseEnter
C. onFocus
D. onChange

6 Why is event.preventDefault() commonly called in a React form submission handler?

Handling form submission workflows Easy
A. To stop the default page reload
B. To disable every submit button
C. To remove all validation rules
D. To clear every form field

7 How can a reusable input component receive its label text?

Reusable form component design Easy
A. Through a browser cookie
B. Through a prop
C. Through a route redirect
D. Through a CSS selector

8 What is a key benefit of creating reusable form field components?

Reusable form component design Easy
A. They replace all validation schemas
B. They keep field behavior consistent
C. They eliminate the need for state
D. They guarantee successful submissions

9 What does conditional rendering allow a React form to do?

Conditional rendering in form interfaces Easy
A. Show elements based on current state
B. Submit data without an event
C. Store input values inside CSS
D. Compile components without JavaScript

10 Which JSX expression displays an error message only when error has a truthy value?

Conditional rendering in form interfaces Easy
A. error || <span>Error</span>
B. error && <span>Error</span>
C. error = <span>Error</span>
D. error + <span>Error</span>

11 Which HTML element should identify the purpose of a form input for users and assistive technologies?

Accessibility considerations in form handling Easy
A. <footer>
B. <label>
C. <canvas>
D. <section>

12 Which attribute can indicate to assistive technologies that an input currently has an invalid value?

Accessibility considerations in form handling Easy
A. aria-expanded
B. aria-invalid
C. aria-hidden
D. aria-checked

13 Where does client-side form validation normally run?

Client-side form validation concepts Easy
A. In the database server
B. In the package registry
C. In the DNS provider
D. In the user's browser

14 Why should an application still validate form data on the server?

Client-side form validation concepts Easy
A. Client-side checks can be bypassed
B. Server validation removes every form error
C. Browser validation changes CSS automatically
D. React state cannot contain text values

15 Which validation rule checks that a field is not left empty?

Commonly used validation patterns Easy
A. Numeric-range validation
B. Cross-field validation
C. Required-field validation
D. Format-pattern validation

16 Which validation pattern is commonly used for a password confirmation field?

Commonly used validation patterns Easy
A. Check that both password labels match
B. Check that both password values match
C. Check that both input types differ
D. Check that both fields are uncontrolled

17 What does a validation schema describe?

Schema-based validation principles Easy
A. The order of rendered React components
B. The expected shape and rules of data
C. The visual theme and colors of a form
D. The network route used by a form

18 What is one benefit of using a shared validation schema?

Schema-based validation principles Easy
A. It centralizes validation rules
B. It automatically styles every input
C. It removes the need for form state
D. It sends every request to the server

19 Which Zod expression defines a required string value?

Form validation using Zod Easy
A. z.number()
B. z.array()
C. z.string()
D. z.boolean()

20 What is a useful result of calling Zod's safeParse when validating form data?

Integrating schema validation with form logic and error handling Easy
A. A component containing labels and input fields
B. A style object containing valid CSS properties
C. A result indicating success or validation errors
D. A request containing headers and cookies

21 A React text input receives its value from component state. Users can type into the input, but the displayed text never changes. Which change most directly fixes the problem?

Controlled and uncontrolled components Medium
A. Replace the value prop with a name prop
B. Add a ref while keeping the state unchanged
C. Read the input value only during component mounting
D. Add an onChange handler that updates the state

22 A form contains a file input and should access the selected file only when the user submits the form. Which approach is most appropriate?

Controlled and uncontrolled components Medium
A. Recreate the file input after every selection
B. Store the file path in a controlled text value
C. Access the file input through a React ref
D. Read the selected file from the submit button

23 A form stores all field values in one object named formData. Which update correctly changes only the email field without removing the other fields?

Form state management patterns Medium
A. setFormData(formData.email = value)
B. setFormData({ email: value })
C. setFormData([...formData, email, value])
D. setFormData({ ...formData, email: value })

24 Several inputs share one change handler and each input has a unique name attribute. Which expression should the handler use to update the matching property in state?

Form state management patterns Medium
A. { ...prev, [event.target.name]: event.target.value }
B. { ...prev, name: event.target.value }
C. { ...prev, value: event.target.name }
D. { ...prev, event.target.name: event.target.value }

25 A React form should validate data and send it with fetch without causing a page reload. What should the submit handler do first?

Handling form submission workflows Medium
A. Call event.target.reset()
B. Call event.preventDefault()
C. Call event.persist()
D. Call event.stopPropagation()

26 A registration form sends an asynchronous request. Which workflow best prevents accidental duplicate submissions?

Handling form submission workflows Medium
A. Clear all fields before starting the request
B. Move the request into each field's change handler
C. Disable submission while the request is pending
D. Hide validation messages until the request finishes

27 A reusable TextField component must display a label, an input, and an error message. Which API best supports reuse across forms?

Reusable form component design Medium
A. Hard-code the field name and validation message
B. Accept label, input props, and an error prop
C. Submit the parent form from inside the component
D. Read every field value from a global variable

28 A custom input component must allow its parent form to focus the underlying DOM input after validation fails. Which React design is most suitable?

Reusable form component design Medium
A. Store the DOM node in ordinary state
B. Expose the input by forwarding a ref
C. Query the input by its visible label
D. Remount the component with a new key

29 A shipping-address section should appear only when useBillingAddress is false. Which JSX condition expresses this requirement?

Conditional rendering in form interfaces Medium
A. useBillingAddress && <ShippingFields />
B. !useBillingAddress || <ShippingFields />
C. !useBillingAddress && <ShippingFields />
D. useBillingAddress || <BillingFields />

30 A form conditionally removes a required companyName field when the user selects "Personal account". What should the form logic generally do with that hidden field?

Conditional rendering in form interfaces Medium
A. Replace its value with the account type label
B. Exclude it from active validation and submission
C. Display its error beside the account type control
D. Keep validating it as a required visible field

31 A text input shows the error message "Email is required" in an element with id="email-error". Which input attribute best creates an accessible relationship to that message?

Accessibility considerations in form handling Medium
A. aria-controls="email-error"
B. aria-label="email-error"
C. aria-hidden="email-error"
D. aria-describedby="email-error"

32 After a failed submission, which behavior most improves keyboard and screen-reader usability when several fields are invalid?

Accessibility considerations in form handling Medium
A. Move focus to the browser's address bar
B. Clear every invalid field and retain current focus
C. Focus the first invalid field and expose its error
D. Disable all fields until the errors disappear

33 A checkout form validates card details in the browser before sending them to the server. Why must the server still validate the submitted data?

Client-side form validation concepts Medium
A. Client-side validation can be bypassed or manipulated
B. Server validation prevents React state from updating
C. Server validation automatically improves input styling
D. Client-side validation cannot display field-level errors

34 A form currently displays validation errors after every keystroke, distracting users before they finish typing. Which strategy offers a more balanced experience?

Client-side form validation concepts Medium
A. Validate all untouched fields on every component render
B. Suppress every validation error until the server responds
C. Reset the entire form whenever one value becomes invalid
D. Validate a field on blur, then revalidate it on change

35 A password confirmation field must match the password field. What kind of validation is required?

Commonly used validation patterns Medium
A. A cross-field equality check
B. A required-attribute check only
C. A whitespace normalization check
D. A single-field type conversion

36 A form accepts an optional website URL. Which rule correctly handles an empty value?

Commonly used validation patterns Medium
A. Accept any nonempty string without checking its format
B. Allow empty input; otherwise require a valid URL
C. Require a valid URL even when the field is empty
D. Convert empty input into a validation error object

37 A team uses the same user schema to validate form data and infer TypeScript types. What is the main benefit of this approach?

Schema-based validation principles Medium
A. It converts uncontrolled inputs into controlled inputs
B. It guarantees that all server requests will succeed
C. It reduces drift between runtime rules and static types
D. It removes the need to handle validation failures

38 A signup form requires password and confirmPassword to match. Why is object-level schema validation appropriate?

Schema-based validation principles Medium
A. The rule depends on values from multiple fields
B. The rule requires direct access to both DOM elements
C. The rule applies only before either field is touched
D. The rule changes both fields into numeric values

39 Given const schema = z.object({ age: z.coerce.number().int().min(18) }), what happens when it validates { age: "21" }?

Form validation using Zod Medium
A. It fails because coercion rejects all strings
B. It fails because min(18) requires 18 digits
C. It succeeds and produces the number 21
D. It succeeds and preserves the string "21"

40 A submit handler uses const result = schema.safeParse(formData). What should it do when result.success is false?

Integrating schema validation with form logic and error handling Medium
A. Throw away the issues and retry with the same data
B. Convert the schema into component state and continue
C. Submit result.data and clear the current errors
D. Map validation issues to fields and skip submission

41 A file input is implemented as a controlled React input by assigning value={fileName} and updating fileName after onChange. What is the most accurate issue with this design?

Controlled and uncontrolled components Hard
A. React cannot observe file input change events
B. The onChange handler only works after form submission
C. File inputs cannot be rendered inside controlled forms
D. Browsers prohibit programmatically setting a file input's value to a nonempty path

42 A controlled text input initially receives value={undefined} and later receives value="admin@example.com". Which behavior should be expected?

Controlled and uncontrolled components Hard
A. The browser automatically converts the value to an empty string
B. React may warn about switching from uncontrolled to controlled
C. React discards the later value update
D. The input remains uncontrolled permanently

43 A form stores values, touched, errors, isSubmitting, and submitError in separate state variables. Several event handlers update multiple variables based on the previous form state. Which refactoring most directly reduces inconsistency risk?

Form state management patterns Hard
A. Replace every state value with a DOM query
B. Use one reducer with explicit form-state actions
C. Move all validation into CSS selectors
D. Store only the latest submitted payload

44 A field update handler is written as setValues({ ...values, [name]: value }), and two updates are queued during the same event. What change best guarantees that both updates use the latest state?

Form state management patterns Hard
A. Use setValues(current => ({ ...current, [name]: value }))
B. Read the value from document.forms[0]
C. Call setValues twice with the same captured object
D. Wrap the handler in useMemo

45 A React form submits data through fetch, but the page still navigates and the browser performs a native submission. Which correction is required?

Handling form submission workflows Hard
A. Call event.preventDefault() at the start of the submit handler
B. Call event.stopPropagation() after the fetch resolves
C. Add async to the component function
D. Set noValidate on the form

46 A user submits a form twice before the first request finishes. Which design most reliably prevents an older response from overwriting newer state?

Handling form submission workflows Hard
A. Use a longer timeout before displaying errors
B. Clear the form immediately after every submit
C. Track a request identifier and accept only the latest response
D. Disable the submit button only after the request succeeds

47 A reusable TextField component needs to support labels, descriptions, errors, arbitrary input attributes, and stable accessibility relationships. Which API design is strongest?

Reusable form component design Hard
A. Use the error text as the input's placeholder
B. Require every parent to assemble raw label and input elements
C. Accept an explicit id, render a linked label, and derive described-by IDs
D. Accept only a visual label and generate IDs from its text

48 A reusable form component exposes onSubmit, onChange, and errors, but it also silently converts server errors into local field errors. What is the main design concern?

Reusable form component design Hard
A. The component cannot render more than one field
B. The component mixes presentation with an undocumented error policy
C. The component has too few CSS classes
D. The component prevents all uncontrolled inputs

49 A billing address section is conditionally removed when sameAsShipping becomes true. When it is shown again, its previous values are gone. Which explanation is most accurate?

Conditional rendering in form interfaces Hard
A. Conditional rendering disables browser form serialization
B. React preserves state only for hidden DOM nodes
C. Checkbox state automatically resets sibling state
D. Unmounting removes the component instance and its local state

50 A payment form renders card fields when method === "card" and bank fields otherwise. Both branches contain an input with the same position but different meanings. What prevents React from incorrectly reusing field state?

Conditional rendering in form interfaces Hard
A. Use distinct key values for the mutually exclusive branches
B. Give both inputs the same name attribute
C. Place both branches inside a fieldset
D. Set autoComplete="off" on both inputs

51 A field has an inline validation message that appears after blur. Which implementation best communicates the error to assistive technologies?

Accessibility considerations in form handling Hard
A. Associate the message with aria-describedby and set aria-invalid="true"
B. Announce every keystroke through an assertive live region
C. Use only a red border and a tooltip
D. Replace the label with the error message

52 A form displays a server-side error summary after submission. What behavior most improves keyboard and screen-reader usability?

Accessibility considerations in form handling Hard
A. Insert the summary without changing focus
B. Reload the page so the browser announces the error
C. Focus the first decorative icon in the form
D. Move focus to a focusable summary heading and preserve field associations

53 Why should client-side validation be treated as a usability feature rather than a security boundary?

Client-side form validation concepts Hard
A. Users can bypass or modify all browser-executed validation logic
B. Client validation cannot detect malformed input
C. Client validation always runs after server validation
D. Browsers ignore validation attributes during submission

54 A password confirmation rule reports an error while the user is still typing the first password. Which validation strategy generally gives the best experience without weakening final correctness?

Commonly used validation patterns Hard
A. Validate only when the two fields are both empty
B. Validate confirmation only after a successful request
C. Validate confirmation on blur and again on submit
D. Validate confirmation only on initial render

55 A numeric field accepts "", "0", and "12" as strings. Which approach avoids incorrectly treating zero as missing while still recognizing an empty field?

Commonly used validation patterns Hard
A. Convert every value with Boolean(value)
B. Use if (!value) to detect missing input
C. Trim first, then test explicitly for an empty string
D. Reject values whose numeric conversion equals zero

56 A schema is used both to validate a form and to transform a text field into a number. What architectural property is most important when using the parsed result?

Schema-based validation principles Hard
A. The schema should mutate the React state object directly
B. The UI should infer validity from the transformed value only
C. The application should use the schema's parsed output as trusted shape-checked data
D. The application should submit the original unparsed object

57 A registration schema validates password and confirmPassword independently, but never checks that they match. What kind of rule is missing?

Schema-based validation principles Hard
A. A primitive type rule
B. A browser autocomplete rule
C. An object-level refinement involving multiple fields
D. A rendering rule for password inputs

58 In Zod, a form field is received from an HTML input as a string, but the domain model requires a positive integer. Which schema best expresses the requirement?

Form validation using Zod Hard
A. z.string().email().positive()
B. z.boolean().int().positive()
C. z.coerce.number().int().positive()
D. z.number().int().positive()

59 A Zod object uses .refine() to ensure confirmPassword matches password, but the resulting issue appears at the form root. Which option gives the best field-level error display?

Form validation using Zod Hard
A. Use z.string() on the entire form instead
B. Provide a path containing "confirmPassword" in the refinement options
C. Convert the issue into a browser alert
D. Remove the refinement and compare values in CSS

60 A form calls schema.parse(values) inside an asynchronous submit handler. Invalid input throws before the handler can populate field errors. Which integration pattern is appropriate?

Integrating schema validation with form logic and error handling Hard
A. Validate only after the server returns a response
B. Catch every error and display the same message globally
C. Ignore the exception and submit the raw values
D. Use safeParse and map result.error.issues into field errors