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?
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> ); }
Think about what the code does when the input is empty.
The code checks if the name is empty and sets an error message. This prevents submission and informs the user.
Choose the code snippet that correctly validates an email string using a regular expression in React Native.
const validateEmail = (email) => {
const regex = /^[\w-.]+@[\w-]+\.[a-z]{2,}$/i;
return regex.test(email);
};Look for the method that returns true or false for regex matching.
The test method on regex returns a boolean indicating if the string matches the pattern. Option D uses it correctly.
In a controlled React Native form, at which points is validation usually triggered?
Think about giving immediate feedback and final checks.
Validation often runs on every input change to give instant feedback and again on submission to ensure all data is valid.
Given this code snippet, why might the validation error message never appear?
const [email, setEmail] = useState(''); const [error, setError] = useState(''); const handleSubmit = () => { if (!email.includes('@')) { error = 'Invalid email'; } else { setError(''); } };
Check how state variables are updated in React.
State variables must be updated using their setter functions. Direct assignment does not update state or trigger re-render.
Why would a developer choose to use a validation schema library such as Yup instead of manual validation functions?
Think about code reuse and clarity in validation logic.
Validation schema libraries let you define rules clearly and reuse them, making validation easier to maintain and test.