Package Exports
- recaptz
- recaptz/dist/recaptz.es.js
- recaptz/dist/recaptz.umd.js
This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (recaptz) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.
Readme
๐ก๏ธ ReCAPTZ
The Modern CAPTCHA Solution for React Applications
A beautiful, customizable, and secure CAPTCHA component with multiple verification types, perfect for protecting your forms and user interactions.
โจ Why Choose ReCAPTZ?
๐ก๏ธ Secure by Design - Built with security best practices and customizable validation rules
โฟ Accessibility First - Screen reader support, keyboard navigation, and audio feedback
โก Developer Friendly - TypeScript support, comprehensive documentation, and easy integration
๐ Zero Dependencies - Minimal bundle size with no external dependencies
๐จ Beautiful Design - Modern UI that works perfectly on mobile and desktop
๐ Internationalization - Built-in support for multiple languages and RTL layouts
๐ฆ Installation
npm install recaptz๐ Quick Start
import { Captcha } from "recaptz";
function LoginForm() {
const [verified, setVerified] = useState(false);
return (
<form>
<input type="email" placeholder="Email" />
<input type="password" placeholder="Password" />
<Captcha
type="numbers"
length={4}
onValidate={setVerified}
validationRules={{
required: true,
allowedCharacters: "0123456789",
}}
/>
<button disabled={!verified}>Login</button>
</form>
);
}๐ฏ CAPTCHA Types
Basic Types
// Numbers only (great for quick verification)
<Captcha type="numbers" length={4} />
// Letters only (alphabetic challenge)
<Captcha type="letters" length={6} />
// Mixed characters (letters + numbers)
<Captcha type="mixed" length={8} />
// Custom character set
<Captcha
customCharacters="ABCDEF123456"
length={5}
caseSensitive={true}
/>Advanced Features
// Timed CAPTCHA (auto-refresh)
<Captcha
type="mixed"
length={5}
refreshInterval={30}
maxAttempts={3}
/>
// Dark mode with success animation
<Captcha
type="letters"
darkMode={true}
showSuccessAnimation={true}
showConfetti={true}
/>
// Accessible CAPTCHA with audio
<Captcha
type="numbers"
enableAudio={true}
autoFocus={true}
/>๐ฃ Custom Hook Usage
Build your own CAPTCHA UI using the useCaptchaState hook:
import { useCaptchaState, CaptchaProvider } from "recaptz";
function CustomCaptcha() {
const {
captchaText,
userInput,
setUserInput,
validate,
refresh,
isValid,
error,
} = useCaptchaState();
return (
<div className="custom-captcha">
{/* Display CAPTCHA */}
<div className="captcha-display">{captchaText}</div>
{/* Input field */}
<input
type="text"
value={userInput}
onChange={(e) => setUserInput(e.target.value)}
placeholder="Enter the code"
className="captcha-input"
/>
{/* Action buttons */}
<div className="captcha-actions">
<button onClick={validate} className="verify-btn">
Verify
</button>
<button onClick={refresh} className="refresh-btn">
Refresh
</button>
</div>
{/* Status display */}
{isValid && <div className="success">โ
Verified!</div>}
{error && <div className="error">โ {error}</div>}
</div>
);
}
// Wrap with provider
function App() {
return (
<CaptchaProvider type="mixed" length={6}>
<CustomCaptcha />
</CaptchaProvider>
);
}Hook Return Values
The useCaptchaState hook returns:
interface CaptchaState {
captchaText: string; // Current CAPTCHA text
userInput: string; // User's input value
setUserInput: (input: string) => void; // Update user input
validate: () => Promise<boolean>; // Validate the input
refresh: () => Promise<void>; // Generate new CAPTCHA
isValid: boolean; // Current validation state
error: string | null; // Current error message
}๐ Real-World Examples
1. Login Form Protection
<Captcha
type="numbers"
length={4}
showSuccessAnimation
maxAttempts={3}
validationRules={{
required: true,
allowedCharacters: "0123456789",
}}
/>2. Contact Form Spam Prevention
<Captcha
type="letters"
length={5}
refreshable
enableAudio
validationRules={{
required: true,
customValidator: (value) =>
/^[a-zA-Z]+$/.test(value) || "Only letters are allowed",
}}
/>3. User Registration
<Captcha
type="mixed"
length={6}
caseSensitive={false}
showSuccessAnimation
maxAttempts={5}
validationRules={{
required: true,
minLength: 6,
maxLength: 6,
}}
/>4. E-commerce Checkout Security
<Captcha
customCharacters="ABCDEF123456"
length={5}
caseSensitive={true}
validationRules={{
required: true,
allowedCharacters: "ABCDEF123456",
customValidator: (value) => {
const hasLetter = /[A-F]/.test(value);
const hasNumber = /[1-6]/.test(value);
return (
(hasLetter && hasNumber) ||
"Must contain at least one letter and one number"
);
},
}}
/>5. Password Reset Protection
<Captcha
type="numbers"
length={6}
refreshInterval={60}
maxAttempts={3}
validationRules={{
required: true,
allowedCharacters: "0123456789",
}}
/>๐ Complete Props Reference
| Prop | Type | Default | Description |
|---|---|---|---|
type |
'numbers' | 'letters' | 'mixed' |
'mixed' |
Type of CAPTCHA to generate |
length |
number |
6 |
Length of CAPTCHA text |
onChange |
(value: string) => void |
- | Callback when input changes |
onValidate |
(isValid: boolean) => void |
- | Callback when validation occurs |
onRefresh |
() => void |
- | Callback when CAPTCHA is refreshed |
onAudioPlay |
() => void |
- | Callback when audio is played |
onError |
(error: string) => void |
- | Callback when error occurs |
onFail |
() => void |
- | Callback when validation fails |
className |
string |
'' |
Additional CSS classes |
customStyles |
React.CSSProperties |
- | Custom inline styles |
inputButtonStyle |
string |
'' |
Input button styles |
refreshable |
boolean |
true |
Whether CAPTCHA can be refreshed |
caseSensitive |
boolean |
false |
Case-sensitive validation |
customCharacters |
string |
- | Custom character set |
validationRules |
ValidationRules |
- | Custom validation rules |
darkMode |
boolean |
false |
Enable dark mode theme |
autoFocus |
boolean |
false |
Auto-focus the input field |
enableAudio |
boolean |
true |
Enable audio support |
showSuccessAnimation |
boolean |
false |
Show success animation |
showConfetti |
boolean |
false |
Show confetti on success |
confettiOptions |
object |
{} |
Confetti configuration |
refreshInterval |
number |
- | Auto-refresh interval in seconds |
maxAttempts |
number |
- | Maximum validation attempts |
rtl |
boolean |
false |
Right-to-left layout |
i18n |
I18nLabels |
- | Internationalization labels |
loadingComponent |
React.ReactNode |
- | Custom loading component |
successComponent |
React.ReactNode |
- | Custom success component |
errorComponent |
React.ReactNode |
- | Custom error component |
theme |
CaptchaTheme |
- | Custom theme configuration |
onSuccess |
() => void |
- | Callback when validation succeeds |
๐ Confetti Configuration
Control the success celebration animation with detailed options:
interface ConfettiOptions {
particleCount?: number; // Number of particles (default: 100)
spread?: number; // Spread angle in degrees (default: 45)
origin?: { x?: number; y?: number }; // Origin point (default: center)
colors?: string[]; // Custom colors array
gravity?: number; // Gravity effect (default: 1)
scalar?: number; // Particle size multiplier (default: 1)
duration?: number; // Animation duration in ms (default: 3000)
}
// Examples
<Captcha
showConfetti={true}
confettiOptions={{
particleCount: 200,
spread: 70,
colors: ['#ff0000', '#00ff00', '#0000ff'],
duration: 5000,
gravity: 0.8,
scalar: 1.2
}}
/>
// Minimal confetti
<Captcha
showConfetti={true}
confettiOptions={{
particleCount: 50,
spread: 30,
colors: ['#gold', '#silver'],
duration: 2000
}}
/>๐ง Custom Components
Replace default components with your own implementations:
// Custom loading spinner
<Captcha
loadingComponent={
<div className="flex items-center gap-2">
<div className="animate-spin rounded-full h-4 w-4 border-b-2 border-blue-600"></div>
<span>Generating CAPTCHA...</span>
</div>
}
/>
// Custom success message
<Captcha
successComponent={
<div className="flex items-center gap-2 text-green-600">
<CheckCircle className="w-5 h-5" />
<span className="font-semibold">Verification Successful!</span>
</div>
}
/>
// Custom error display
<Captcha
errorComponent={({ error, severity }) => (
<div className={`p-3 rounded-lg ${
severity === 'high' ? 'bg-red-100 text-red-800' :
severity === 'medium' ? 'bg-yellow-100 text-yellow-800' :
'bg-blue-100 text-blue-800'
}`}>
<AlertTriangle className="w-4 h-4 inline mr-2" />
{error}
</div>
)}
/>๐ Event Handling
Comprehensive event tracking for analytics and debugging:
const [events, setEvents] = useState([]);
const handleCaptchaEvents = {
onChange: (value) => {
console.log("Input changed:", value);
setEvents((prev) => [
...prev,
{ type: "input", value, timestamp: Date.now() },
]);
},
onValidate: (isValid) => {
console.log("Validation result:", isValid);
setEvents((prev) => [
...prev,
{
type: "validation",
success: isValid,
timestamp: Date.now(),
},
]);
},
onRefresh: () => {
console.log("CAPTCHA refreshed");
setEvents((prev) => [...prev, { type: "refresh", timestamp: Date.now() }]);
},
onAudioPlay: () => {
console.log("Audio played");
setEvents((prev) => [...prev, { type: "audio", timestamp: Date.now() }]);
},
onError: (error) => {
console.error("CAPTCHA error:", error);
setEvents((prev) => [
...prev,
{
type: "error",
message: error,
timestamp: Date.now(),
},
]);
},
onFail: () => {
console.log("Validation failed");
setEvents((prev) => [...prev, { type: "fail", timestamp: Date.now() }]);
},
onSuccess: () => {
console.log("Validation succeeded");
setEvents((prev) => [...prev, { type: "success", timestamp: Date.now() }]);
},
};
<Captcha
{...handleCaptchaEvents}
maxAttempts={3}
showSuccessAnimation={true}
showConfetti={true}
/>;๐ง Validation Rules
interface ValidationRules {
minLength?: number;
maxLength?: number;
allowedCharacters?: string;
required?: boolean;
caseSensitive?: boolean;
customValidator?: (value: string) => boolean | string;
}
// Example with complex validation
<Captcha
validationRules={{
required: true,
minLength: 4,
maxLength: 8,
allowedCharacters: "ABCDEF123456",
customValidator: (value) => {
const hasLetter = /[A-F]/.test(value);
const hasNumber = /[1-6]/.test(value);
if (!hasLetter) return "Must contain at least one letter";
if (!hasNumber) return "Must contain at least one number";
return true;
},
}}
/>;๐ Internationalization
Built-in Language Support
// German
<Captcha
i18n={{
securityCheck: "Sicherheitsรผberprรผfung",
listenToCaptcha: "CAPTCHA anhรถren",
refreshCaptcha: "CAPTCHA neu laden",
inputPlaceholder: "Code eingeben",
verifyButton: "Prรผfen",
verificationSuccessful: "Erfolg!",
captchaRequired: "Bitte CAPTCHA eingeben",
captchaDoesNotMatch: "CAPTCHA stimmt nicht รผberein",
}}
/>
// Spanish
<Captcha
i18n={{
securityCheck: "Verificaciรณn de seguridad",
listenToCaptcha: "Escuchar CAPTCHA",
refreshCaptcha: "Actualizar CAPTCHA",
inputPlaceholder: "Ingrese el cรณdigo",
verifyButton: "Verificar",
verificationSuccessful: "ยกรxito!",
captchaRequired: "Por favor ingrese el CAPTCHA",
captchaDoesNotMatch: "El CAPTCHA no coincide",
}}
/>
// Arabic (RTL)
<Captcha
rtl={true}
i18n={{
securityCheck: "ูุญุต ุงูุฃู
ุงู",
inputPlaceholder: "ุฃุฏุฎู ุงูุฑู
ุฒ",
verifyButton: "ุชุญูู",
refreshCaptcha: "ุฑู
ุฒ ุฌุฏูุฏ",
}}
/>๐จ Styling & Customization
Custom Themes
// Light theme with custom styles
<Captcha
className="my-custom-captcha"
customStyles={{
backgroundColor: '#f8f9fa',
borderRadius: '12px',
padding: '20px',
boxShadow: '0 4px 12px rgba(0,0,0,0.1)'
}}
/>
// Dark theme
<Captcha
darkMode={true}
customStyles={{
backgroundColor: '#1a1a1a',
border: '1px solid #333',
borderRadius: '8px',
}}
/>CSS Customization
.my-custom-captcha {
border-radius: 12px;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}
.my-custom-captcha input {
border-radius: 8px;
border: 2px solid #e1e5e9;
padding: 12px;
font-size: 16px;
}
.my-custom-captcha button {
background: #4caf50;
color: white;
border: none;
border-radius: 8px;
padding: 12px 24px;
cursor: pointer;
transition: all 0.2s;
}
.my-custom-captcha button:hover {
background: #45a049;
transform: translateY(-1px);
}โฟ Accessibility Features
ReCAPTZ is built with accessibility as a priority:
- ๐ Audio Support - Text-to-speech for visually impaired users
- โจ๏ธ Keyboard Navigation - Full keyboard support with proper focus management
- ๐ท๏ธ ARIA Labels - Comprehensive screen reader support
- ๐จ High Contrast - Works with high contrast and dark modes
- ๐ฑ Mobile Friendly - Touch-optimized for mobile devices
// Enable all accessibility features
<Captcha
enableAudio={true}
autoFocus={true}
i18n={{
pressSpaceToHearCode: "Press Space to hear the code",
enterToValidate: "Press Enter to validate",
escToClear: "Press Escape to clear",
}}
/>Keyboard Shortcuts
| Key | Action |
|---|---|
Space |
Hear the CAPTCHA code |
Enter |
Validate the input |
Escape |
Clear the input |
๐ ๏ธ Implementation Tips
1. Customize for Context
Adjust difficulty and type based on the sensitivity of the action:
- Login forms: Simple numbers (4 digits)
- Registration: Mixed characters (6 length)
- High-value transactions: Custom validation with complex rules
2. Consider Accessibility
Always enable audio support and provide clear instructions:
<Captcha enableAudio={true} autoFocus={true} />3. Balance Security & UX
Use appropriate attempt limits and timeouts:
<Captcha maxAttempts={3} refreshInterval={30} />๐ฆ TypeScript Support
Full TypeScript support with comprehensive type definitions:
import type { CaptchaProps, ValidationRules, I18nLabels } from "recaptz";
const customValidation: ValidationRules = {
required: true,
minLength: 4,
customValidator: (value: string) => {
return value.length >= 4 || "Minimum 4 characters required";
},
};
const labels: I18nLabels = {
securityCheck: "Security Verification",
inputPlaceholder: "Enter code here",
verifyButton: "Verify Code",
};๐ Browser Support
Works seamlessly across all modern browsers:
- Chrome (Latest)
- Firefox (Latest)
- Safari (Latest)
- Edge (Latest)
- Opera (Latest)
๐ค Contributing
We welcome contributions! Please see our Contributing Guide for details.
Development Setup
- Fork the repository
- Clone your fork:
git clone https://github.com/ShejanMahamud/recaptz.git - Install dependencies:
npm install - Start development:
npm run dev - Make your changes and test thoroughly
- Submit a pull request
๐ License
MIT ยฉ Shejan Mahamud
๐ Support & Community
- ๐ Report Issues
- ๐ฌ Discussions
- ๐ Documentation
- ๐ฏ Examples
๐ Acknowledgments
Special thanks to all contributors and the React community for their support and feedback.
Made with โค๏ธ by Shejan Mahamud
Secure your applications with confidence using ReCAPTZ ๐ก๏ธ