Bird
Raised Fist0
React Nativemobile~20 mins

Form validation patterns in React Native - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Form Validation Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ ui_behavior
intermediate
2:00remaining
What happens when submitting a form with empty required fields?

Consider a React Native form with required text inputs and a submit button. What is the expected behavior when the user taps submit without filling any required fields?

React Native
import React, { useState } from 'react';
import { View, TextInput, Button, Text } from 'react-native';

export default function MyForm() {
  const [name, setName] = useState('');
  const [error, setError] = useState('');

  const handleSubmit = () => {
    if (!name) {
      setError('Name is required');
    } else {
      setError('');
      // proceed with submission
    }
  };

  return (
    <View>
      <TextInput
        placeholder="Name"
        value={name}
        onChangeText={setName}
        accessibilityLabel="Name input"
      />
      {error ? <Text accessibilityLiveRegion="polite" style={{color: 'red'}}>{error}</Text> : null}
      <Button title="Submit" onPress={handleSubmit} accessibilityLabel="Submit form" />
    </View>
  );
}
AThe form shows an error message below the input and does not submit.
BThe form submits successfully even if the input is empty.
CThe app crashes due to missing input validation.
DThe input field automatically fills with a default value.
Attempts:
2 left
💡 Hint

Think about what the code does when the input is empty.

📝 Syntax
intermediate
2:00remaining
Which option correctly validates an email format in React Native?

Choose the code snippet that correctly validates an email string using a regular expression in React Native.

React Native
const validateEmail = (email) => {
  const regex = /^[\w-.]+@[\w-]+\.[a-z]{2,}$/i;
  return regex.test(email);
};
Aconst validateEmail = email => email.test(/^[\w-.]+@[\w-]+\.[a-z]{2,}$/i);
Bconst validateEmail = email => email.match(/^[\w-.]+@[\w-]+\.[a-z]{2,}$/i);
Cconst validateEmail = email => email.includes('@') && email.includes('.');
Dconst validateEmail = email => /^[\w-.]+@[\w-]+\.[a-z]{2,}$/i.test(email);
Attempts:
2 left
💡 Hint

Look for the method that returns true or false for regex matching.

❓ lifecycle
advanced
2:00remaining
When does form validation typically run in React Native controlled components?

In a controlled React Native form, at which points is validation usually triggered?

AOnly when the input loses focus (blur event).
BOn every input change and on form submission.
COnly when the component mounts.
DOnly when the user submits the form.
Attempts:
2 left
💡 Hint

Think about giving immediate feedback and final checks.

🔧 Debug
advanced
2:00remaining
Why does this React Native form not show validation errors?

Given this code snippet, why might the validation error message never appear?

React Native
const [email, setEmail] = useState('');
const [error, setError] = useState('');

const handleSubmit = () => {
  if (!email.includes('@')) {
    error = 'Invalid email';
  } else {
    setError('');
  }
};
ABecause the error state is assigned directly instead of using setError.
BBecause the email state is not updated on input change.
CBecause the includes method is not valid on strings.
DBecause the handleSubmit function is never called.
Attempts:
2 left
💡 Hint

Check how state variables are updated in React.

🧠 Conceptual
expert
2:00remaining
What is the main advantage of using a validation schema library like Yup in React Native forms?

Why would a developer choose to use a validation schema library such as Yup instead of manual validation functions?

AIt automatically fixes invalid inputs without user interaction.
BIt removes the need to handle form state in React Native.
CIt provides a declarative and reusable way to define complex validation rules and error messages.
DIt disables the submit button until all inputs are valid without extra code.
Attempts:
2 left
💡 Hint

Think about code reuse and clarity in validation logic.

Practice

(1/5)
1. What is the main purpose of form validation in a React Native app?
easy
A. To check user input and show errors if needed
B. To change the app's theme colors
C. To speed up the app loading time
D. To add animations to buttons

Solution

  1. Step 1: Understand form validation role

    Form validation is used to check if user input is correct or complete.
  2. Step 2: Identify the correct purpose

    Only To check user input and show errors if needed describes checking input and showing errors, which is the main goal.
  3. Final Answer:

    To check user input and show errors if needed -> Option A
  4. Quick Check:

    Form validation = check input and show errors [OK]
Hint: Form validation means checking input for mistakes [OK]
Common Mistakes:
  • Confusing validation with UI styling
  • Thinking validation speeds app loading
  • Mixing validation with animations
2. Which of the following is the correct way to define a simple validation function in React Native?
easy
A. validate = (text) => { text.length > 0 ? 'Error' : ''; }
B. function validate(text) { return text.length < 0 ? 'Error' : ''; }
C. const validate = (text) => text.length > 0 ? '' : 'Required';
D. const validate = text => { if text.length = 0 return 'Error'; }

Solution

  1. Step 1: Check syntax correctness

    const validate = (text) => text.length > 0 ? '' : 'Required'; uses correct arrow function syntax and returns empty string if valid.
  2. Step 2: Identify logical correctness

    const validate = (text) => text.length > 0 ? '' : 'Required'; returns 'Required' if text is empty, which is expected behavior.
  3. Final Answer:

    const validate = (text) => text.length > 0 ? '' : 'Required'; -> Option C
  4. Quick Check:

    Correct arrow function with conditional return = const validate = (text) => text.length > 0 ? '' : 'Required'; [OK]
Hint: Arrow functions with conditional return are common for validation [OK]
Common Mistakes:
  • Using assignment '=' instead of comparison '==' or '==='
  • Missing return statements in function
  • Incorrect arrow function syntax
3. Given this code snippet, what will be the value of error after calling validate('')?
const validate = (text) => {
  if (text.trim() === '') {
    return 'Field cannot be empty';
  }
  return '';
};
const error = validate('');
medium
A. null
B. '' (empty string)
C. undefined
D. 'Field cannot be empty'

Solution

  1. Step 1: Analyze the input to validate function

    The input is an empty string ''. The trim() method removes spaces but here input is already empty.
  2. Step 2: Follow the if condition logic

    Since text.trim() === '', the function returns 'Field cannot be empty'.
  3. Final Answer:

    'Field cannot be empty' -> Option D
  4. Quick Check:

    Empty input triggers error message [OK]
Hint: Empty strings trigger error messages in validation [OK]
Common Mistakes:
  • Assuming empty string returns empty error
  • Ignoring trim() effect
  • Confusing return values
4. Identify the error in this validation function:
const validateEmail = (email) => {
  if (!email.includes('@')) {
    'Invalid email';
  }
  return '';
};
medium
A. Missing return statement inside if block
B. Using includes() is incorrect for email validation
C. Function should be async
D. Return statement should be outside the function

Solution

  1. Step 1: Check if error message is returned

    The if block has a string 'Invalid email' but no return keyword, so it does nothing.
  2. Step 2: Understand function flow

    Because no return in if, function always returns empty string, ignoring errors.
  3. Final Answer:

    Missing return statement inside if block -> Option A
  4. Quick Check:

    Return missing in if block causes no error shown [OK]
Hint: Always return error messages inside conditions [OK]
Common Mistakes:
  • Forgetting return keyword in if block
  • Assuming string alone returns value
  • Misusing async when not needed
5. You want to validate a password field that must be at least 8 characters and contain a number. Which validation function correctly implements this?
hard
A. const validatePassword = (pwd) => pwd.length >= 8 || /\d/.test(pwd) ? '' : 'Password must be 8+ chars and include a number';
B. const validatePassword = (pwd) => { if (pwd.length < 8) return 'Too short'; if (!/\d/.test(pwd)) return 'No number'; return ''; };
C. const validatePassword = (pwd) => { if (pwd.length > 8 || /\d/.test(pwd)) return ''; else return 'Invalid'; };
D. const validatePassword = (pwd) => pwd.length > 8 && /\d/.test(pwd) ? 'Valid' : 'Invalid';

Solution

  1. Step 1: Check each condition separately

    const validatePassword = (pwd) => { if (pwd.length < 8) return 'Too short'; if (!/\d/.test(pwd)) return 'No number'; return ''; }; checks length first, returns 'Too short' if less than 8, then checks for number, returns 'No number' if missing.
  2. Step 2: Confirm final return for valid password

    If both conditions pass, it returns empty string meaning no error, which is correct.
  3. Final Answer:

    const validatePassword = (pwd) => { if (pwd.length < 8) return 'Too short'; if (!/\d/.test(pwd)) return 'No number'; return ''; }; -> Option B
  4. Quick Check:

    Separate checks with returns for each error = const validatePassword = (pwd) => { if (pwd.length < 8) return 'Too short'; if (!/\d/.test(pwd)) return 'No number'; return ''; }; [OK]
Hint: Check each rule separately and return specific errors [OK]
Common Mistakes:
  • Using OR instead of AND for conditions
  • Returning success message instead of empty string
  • Combining conditions incorrectly
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard