ackerjs-forms
v1.0.0
Published
Client-side form handling with built-in SMTP email capabilities for AckerJS
Downloads
5
Maintainers
Readme
AckerJS Forms
Client-side form handling with built-in SMTP email capabilities
✨ Features
- 🚀 Zero Backend Setup - Works immediately after installation
- 📧 Built-in SMTP Client - Send emails directly from the browser
- ✅ Automatic Validation - Auto-detect validation rules from HTML attributes
- 🎨 Template Engine - Customizable email templates with variable substitution
- 🔒 Security First - Built-in sanitization and XSS protection
- 💪 TypeScript Support - Fully typed API
- 📦 Tree-shakable - Import only what you need
- 🎯 Framework Agnostic - Works with vanilla JS, React, Vue, or any framework
📦 Installation
npm install ackerjs-forms🚀 Quick Start
Basic Usage
<form id="contact-form">
<input type="text" name="name" required minlength="3" />
<input type="email" name="email" required />
<textarea name="message" required minlength="10"></textarea>
<button type="submit">Send</button>
</form>import { AckerForm } from 'ackerjs-forms';
const form = new AckerForm('#contact-form', {
smtp: {
host: 'smtp.gmail.com',
port: 587,
secure: false,
auth: {
user: '[email protected]',
pass: 'your-app-password'
}
},
email: {
to: '[email protected]',
subject: 'New Contact Form Submission',
userConfirmation: true
},
onSuccess: (data) => {
console.log('Form submitted successfully!', data);
},
onError: (error) => {
console.error('Submission failed:', error);
}
});📚 Core Concepts
1. Auto-Detection of Validation Rules
AckerJS Forms automatically detects validation rules from HTML5 attributes:
<input type="text" name="username" required minlength="3" maxlength="20" />
<input type="email" name="email" required />
<input type="url" name="website" pattern="https?://.+" />
<input type="number" name="age" min="18" max="100" />These attributes are automatically converted to validation rules!
2. Custom Validation Rules
Add custom validation logic:
form.addRule('phone', {
validator: (value) => /^\+?[1-9]\d{1,14}$/.test(value),
message: 'Please enter a valid phone number'
});
form.addRule('password', {
validator: (value) => {
return value.length >= 8 && /[A-Z]/.test(value) && /[0-9]/.test(value);
},
message: 'Password must be at least 8 characters with uppercase and number'
});3. SMTP Configuration
Configure SMTP for sending emails:
const form = new AckerForm('#myform', {
smtp: {
host: 'smtp.gmail.com', // SMTP server
port: 587, // SMTP port (587 for TLS, 465 for SSL)
secure: false, // true for 465, false for other ports
auth: {
user: '[email protected]',
pass: 'your-app-password' // Use app-specific passwords!
}
}
});Popular SMTP Providers
Gmail:
{
host: 'smtp.gmail.com',
port: 587,
secure: false,
auth: { user: '[email protected]', pass: 'app-password' }
}Outlook/Office365:
{
host: 'smtp-mail.outlook.com',
port: 587,
secure: false,
auth: { user: '[email protected]', pass: 'password' }
}SendGrid:
{
host: 'smtp.sendgrid.net',
port: 587,
secure: false,
auth: { user: 'apikey', pass: 'your-sendgrid-api-key' }
}4. Email Templates
Using Built-in Templates
const form = new AckerForm('#myform', {
email: {
to: '[email protected]',
subject: 'New Submission',
template: 'default/welcome', // Use built-in template
userConfirmation: true, // Send confirmation to user
userTemplate: 'default/developer-alert'
}
});Custom Templates
Create your own email templates with variable substitution:
<!-- my-template.html -->
<html>
<body>
<h1>Hello {{name}}!</h1>
<p>Thank you for your message: {{message}}</p>
<p>We'll contact you at {{email}}</p>
</body>
</html>const form = new AckerForm('#myform', {
email: {
template: '/path/to/my-template.html'
}
});Template Syntax
Variables:
{{fieldName}} <!-- Replace with form data -->
{{user.email}} <!-- Nested properties -->Conditionals:
{{#if fieldName}}
<p>{{fieldName}}</p>
{{/if}}Loops:
{{#each items}}
<li>{{this}}</li>
{{/each}}5. Lifecycle Events
Hook into form submission lifecycle:
const form = new AckerForm('#myform', {
onSubmit: (data) => {
console.log('Form submitted with:', data);
// Return false to cancel submission
},
onValidate: (result) => {
console.log('Validation result:', result);
// result.valid: boolean
// result.errors: { fieldName: 'error message' }
},
onSuccess: (response) => {
console.log('Emails sent successfully:', response);
// response.userEmail: string
// response.developerEmail: string
},
onError: (error) => {
console.error('Submission failed:', error);
}
});6. Security Features
AckerJS Forms includes built-in security:
import { Sanitizer } from 'ackerjs-forms';
// Escape HTML to prevent XSS
const safe = Sanitizer.escapeHtml(userInput);
// Strip all HTML tags
const text = Sanitizer.stripHtml(htmlContent);
// Strip dangerous scripts and attributes
const clean = Sanitizer.stripScripts(htmlContent);
// Validate and sanitize emails
const isValid = Sanitizer.isValidEmail(email);
const sanitized = Sanitizer.sanitizeEmail(email);
// Sanitize entire form data
const cleanData = Sanitizer.sanitizeFormData(formData);🔧 Advanced Usage
Manual Validation
import { Validator } from 'ackerjs-forms';
const validator = new Validator();
validator.addRule('email', {
required: true,
email: true
});
validator.addRule('age', {
required: true,
min: 18,
max: 100
});
const result = validator.validateForm({
email: '[email protected]',
age: 25
});
if (result.valid) {
console.log('Valid!');
} else {
console.log('Errors:', result.errors);
}Custom Template Rendering
import { TemplateRenderer } from 'ackerjs-forms';
const renderer = new TemplateRenderer();
const html = await renderer.render('/path/to/template.html', {
name: 'John',
email: '[email protected]',
items: ['Item 1', 'Item 2', 'Item 3']
});Using the SMTP Client Directly
import { SMTPClient, MIMEBuilder } from 'ackerjs-forms';
const smtp = new SMTPClient({
host: 'smtp.gmail.com',
port: 587,
secure: false,
auth: {
user: '[email protected]',
pass: 'your-app-password'
}
});
const message = MIMEBuilder.buildMessage({
from: '[email protected]',
to: '[email protected]',
subject: 'Test Email',
text: 'Plain text content',
html: '<h1>HTML content</h1>'
});
await smtp.sendMail(message);📖 API Reference
AckerForm
Main form handler class.
new AckerForm(selector: string, options: AckerFormOptions)Options:
smtp- SMTP configurationemail- Email settings (to, subject, templates)validation- Validation optionsui- UI customizationonSubmit- Submit handleronValidate- Validation handleronSuccess- Success handleronError- Error handler
Methods:
addRule(fieldName, rule)- Add custom validation rulevalidate()- Manually validate formsubmit()- Manually submit formreset()- Reset formdestroy()- Cleanup and remove event listeners
Validator
Form validation engine.
new Validator()Methods:
addRule(fieldName, rule)- Add validation rulevalidateField(fieldName, value)- Validate single fieldvalidateForm(data)- Validate entire formgetErrors()- Get all validation errors
TemplateRenderer
Email template renderer with variable substitution.
new TemplateRenderer()Methods:
render(templatePath, data)- Render template with dataloadTemplate(url)- Load template from URL
SMTPClient
SMTP client for sending emails.
new SMTPClient(config: SMTPConfig)Methods:
sendMail(message)- Send email message
Sanitizer
Security utilities for sanitizing input.
Static Methods:
Sanitizer.escapeHtml(text)- Escape HTML special charactersSanitizer.stripHtml(html)- Remove all HTML tagsSanitizer.stripScripts(html)- Remove scripts and dangerous attributesSanitizer.sanitizeEmail(email)- Sanitize email addressSanitizer.isValidEmail(email)- Validate email formatSanitizer.sanitizeFormData(data)- Sanitize all form data
🔐 Security Best Practices
- Never expose SMTP credentials in client-side code - Use environment variables or a backend proxy
- Always validate and sanitize user input - Built-in but you can add custom rules
- Use app-specific passwords - Don't use your actual email password
- Enable rate limiting - Prevent abuse of your SMTP server
- Validate email domains - Use
isEmailFromDomain()helper - Check for disposable emails - Use
isDisposableEmail()helper
🤝 Integration with AckerJS
AckerJS Forms works seamlessly with the AckerJS framework:
import { dom } from 'ackerjs';
import { AckerForm } from 'ackerjs-forms';
// Use AckerJS DOM utilities
dom.on('#myform', 'submit', (e) => {
e.preventDefault();
form.submit();
});
// Use AckerJS HTTP utilities for backend integration
import { http } from 'ackerjs';
const form = new AckerForm('#myform', {
onSuccess: async (data) => {
// Send data to your backend
await http.post('/api/submissions', data);
}
});📝 Examples
Check out the /examples directory for complete working examples:
- Basic contact form
- Multi-step form with validation
- File upload handling
- Custom email templates
- Integration with React
- Integration with Vue
- Backend proxy setup
🐛 Troubleshooting
Emails not sending
- Check SMTP credentials are correct
- Verify SMTP port and secure settings
- Check console for error messages
- Test SMTP connection outside the browser first
Validation not working
- Ensure HTML attributes are spelled correctly
- Check for JavaScript errors in console
- Verify field names match validation rules
Template not loading
- Check template file path is correct
- Verify file is accessible via HTTP
- Check browser console for CORS errors
📄 License
MIT © Acker Technologies
