Form validation helps check if the user entered the right information before sending it. It stops mistakes and makes apps easier to use.
Form validation patterns in React Native
const validate = (value) => {
if (!value) return 'Field is required';
if (value.length < 3) return 'Too short';
return '';
};Validation functions usually take the input value and return an error message or empty string.
You can use simple if checks or regular expressions for patterns.
const validateEmail = (email) => {
const regex = /^[\w.-]+@[\w-]+\.[a-z]{2,}$/i;
if (!email) return 'Email is required';
if (!regex.test(email)) return 'Invalid email';
return '';
};const validatePassword = (password) => {
if (!password) return 'Password is required';
if (password.length < 6) return 'Password too short';
return '';
};const validateConfirmPassword = (password, confirm) => {
if (confirm !== password) return 'Passwords do not match';
return '';
};This React Native app has an email input and a submit button. When you press submit, it checks if the email is empty or wrong. If valid, it shows an alert. If not, it shows an error message in red below the input.
import React, { useState } from 'react'; import { View, TextInput, Text, Button, Alert } from 'react-native'; export default function App() { const [email, setEmail] = useState(''); const [error, setError] = useState(''); const validateEmail = (value) => { const regex = /^[\w.-]+@[\w-]+\.[a-z]{2,}$/i; if (!value) return 'Email is required'; if (!regex.test(value)) return 'Invalid email'; return ''; }; const handleSubmit = () => { const errorMsg = validateEmail(email); setError(errorMsg); if (!errorMsg) { Alert.alert('Success', 'Email is valid!'); } }; return ( <View style={{ padding: 20 }}> <TextInput placeholder="Enter your email" value={email} onChangeText={setEmail} keyboardType="email-address" autoCapitalize="none" style={{ borderWidth: 1, borderColor: '#ccc', padding: 10, marginBottom: 5 }} accessibilityLabel="Email input" /> {error ? <Text style={{ color: 'red' }}>{error}</Text> : null} <Button title="Submit" onPress={handleSubmit} accessibilityLabel="Submit button" /> </View> ); }
Always give clear error messages so users know what to fix.
Validate on submit or as the user types for better experience.
Use accessibility labels so screen readers can describe inputs and errors.
Form validation checks user input to prevent mistakes.
Use simple functions to return error messages or empty strings.
Show errors clearly and use accessibility features for all users.
Practice
Solution
Step 1: Understand form validation role
Form validation is used to check if user input is correct or complete.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.Final Answer:
To check user input and show errors if needed -> Option AQuick Check:
Form validation = check input and show errors [OK]
- Confusing validation with UI styling
- Thinking validation speeds app loading
- Mixing validation with animations
Solution
Step 1: Check syntax correctness
const validate = (text) => text.length > 0 ? '' : 'Required'; uses correct arrow function syntax and returns empty string if valid.Step 2: Identify logical correctness
const validate = (text) => text.length > 0 ? '' : 'Required'; returns 'Required' if text is empty, which is expected behavior.Final Answer:
const validate = (text) => text.length > 0 ? '' : 'Required'; -> Option CQuick Check:
Correct arrow function with conditional return = const validate = (text) => text.length > 0 ? '' : 'Required'; [OK]
- Using assignment '=' instead of comparison '==' or '==='
- Missing return statements in function
- Incorrect arrow function syntax
error after calling validate('')?
const validate = (text) => {
if (text.trim() === '') {
return 'Field cannot be empty';
}
return '';
};
const error = validate('');Solution
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.Step 2: Follow the if condition logic
Since text.trim() === '', the function returns 'Field cannot be empty'.Final Answer:
'Field cannot be empty' -> Option DQuick Check:
Empty input triggers error message [OK]
- Assuming empty string returns empty error
- Ignoring trim() effect
- Confusing return values
const validateEmail = (email) => {
if (!email.includes('@')) {
'Invalid email';
}
return '';
};Solution
Step 1: Check if error message is returned
The if block has a string 'Invalid email' but no return keyword, so it does nothing.Step 2: Understand function flow
Because no return in if, function always returns empty string, ignoring errors.Final Answer:
Missing return statement inside if block -> Option AQuick Check:
Return missing in if block causes no error shown [OK]
- Forgetting return keyword in if block
- Assuming string alone returns value
- Misusing async when not needed
Solution
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.Step 2: Confirm final return for valid password
If both conditions pass, it returns empty string meaning no error, which is correct.Final Answer:
const validatePassword = (pwd) => { if (pwd.length < 8) return 'Too short'; if (!/\d/.test(pwd)) return 'No number'; return ''; }; -> Option BQuick 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]
- Using OR instead of AND for conditions
- Returning success message instead of empty string
- Combining conditions incorrectly
Ready to prove it?
Pass the test and this pattern moves unknown
