Documentation
Class: Form
Description:
The Form
component is a reusable React component responsible for rendering and handling form submissions. It provides a flexible structure for creating various types of forms, including simple contact forms and more complex multi-step forms.
Props:
fields
: An array of strings representing the names of the form fields.onValidate
: A function that handles validation and submission logic for the form. It receives the form's element object as an argument.header
: A React element that renders above the form fields.footer
: A React element that renders below the form fields.success
: A React element that renders if the form submission is successful.error
: A React element that renders if the form submission fails.text
: A string representing the button text.showPassPolicy
: A boolean indicating whether to display the password policy hint.defaults
: An object containing default values for the form fields.autoFocus
: A boolean indicating whether to automatically focus on the first form field.readOnlyFields
: An array of strings representing the names of readonly fields.highlight
: A boolean indicating whether to use the default button styles.msgLabel
: A string representing the label for the message field.
Example:
import Form from "./Form";
const MyForm = () => {
const fields = ["name", "email", "message"];
const onValidate = async (elements) => {
// Perform form validation and submit data here
console.log(elements);
return true;
};
return (
<Form
fields={fields}
onValidate={onValidate}
header={<h1>Contact Us</h1>}
footer={<p>Thank you for your message!</p>}
/>
);
};
Methods
Method: submitForm
Description:
This method is triggered when the form is submitted. It handles preventing default form submission behavior, clearing any existing errors, validating form inputs, and calling the onValidate
function to handle submission logic.
Parameters:
e
: The event object associated with the form submission.
Returns:
void
Example:
// Inside the Form component
const submitForm = async (e) => {
e.preventDefault();
clearErrors();
if (e.type === "click") e.target = e.target.closest("form");
if (!validateInput(e.target.elements)) return;
// if-condition prevents visual updates in non-modal (CTA) forms
if (props.success) setStatus(FormStatus.BUSY);
const result = await props.onValidate(e.target.elements);
if (!props.success) return;
result ? setStatus(FormStatus.SENT) : setStatus(FormStatus.ERROR);
};
Method: clearErrors
Description: This method clears all error messages from the form fields.
Parameters:
- None
Returns:
void
Example:
// Inside the Form component
const clearErrors = () => {
props.fields.forEach((field) => updateErrors(field, ErrorStatus.NONE, ""));
};
Method: updateErrors
Description: This method updates the error status and message for a specific form field.
Parameters:
key
: The name of the form field.status
: The new error status for the field.msg
: The new error message for the field.
Returns:
void
Example:
// Inside the Form component
const updateErrors = (key, status, msg) => {
if (
status === ErrorStatus.INACTIVE &&
errors[key].status !== ErrorStatus.ACTIVE
) {
return;
}
setErrors((error) => ({
...error,
[key]: {
status: status,
message: typeof msg !== "undefined" ? msg : errors[key].message,
},
}));
};
Method: validateInput
Description: This method validates all form inputs based on the defined validation rules. It iterates through each field and applies the corresponding validation tests.
Parameters:
elements
: The form's element object.
Returns:
boolean
: True if all inputs are valid, false otherwise.
Example:
// Inside the Form component
const validateInput = (elements) => {
let pass = true;
for (const field of props.fields) {
for (const test of validations[field]) {
const value = elements[field].value;
const error = test(value);
if (error) {
updateErrors(field, ErrorStatus.ACTIVE, error);
pass = false;
break;
}
}
}
return pass;
};
Method: getType
Description: This method determines the input type for a given form field based on its name. It handles special cases for message fields and password fields.
Parameters:
field
: The name of the form field.
Returns:
string
: The input type for the field.
Example:
// Inside the Form component
const getType = (field) => {
if (field === "message") return "textarea";
if (field === "password" && !showPass) return "password";
return "text";
};
Method: onIconClick
Description:
This method is used as an event handler for the password visibility icon. It toggles the showPass
state, which controls whether the password field displays as text or password input.
Parameters:
- None
Returns:
void
Example:
// Inside the Form component
const onIconClick = () => setShowPass(!showPass);
Function: isBlank
Description: This function checks if a given value is blank. If the value is empty or null, it returns an error message indicating that the field is blank.
Parameters:
value
: The value to check.
Returns:
string
: An error message if the value is blank, ornull
otherwise.
Example:
// Inside the Form component
const isBlank = (value) => {
return value ? null : ErrorMsg.FIELD_BLANK;
};
Function: isInvalidEmail
Description: This function checks if a given email address is invalid using a regular expression. If the email address is invalid, it returns an error message indicating that the email is invalid.
Parameters:
value
: The email address to check.
Returns:
string
: An error message if the email address is invalid, ornull
otherwise.
Example:
// Inside the Form component
const isInvalidEmail = (value) => {
return validEmailPattern.test(value) ? null : ErrorMsg.EMAIL_INVALID;
};
Function: isPersonalEmail
Description:
This function checks if a given email address belongs to a personal domain. It extracts the domain name from the email and checks if it's included in the PERSONAL_DOMAINS
array. If it's a personal domain, it returns an error message indicating that the email is a personal address.
Parameters:
email
: The email address to check.
Returns:
string
: An error message if the email address is a personal domain, ornull
otherwise.
Example:
// Inside the Form component
const isPersonalEmail = (email) => {
const domain = email.split("@")[1].split(".")[0];
return PERSONAL_DOMAINS.includes(domain) ? ErrorMsg.EMAIL_PERSONAL : null;
};
Function: isShortPassword
Description:
This function checks if a given password is too short. If the password length is less than the MIN_PASS_LEN
, it returns an error message indicating that the password is too short.
Parameters:
value
: The password to check.
Returns:
string
: An error message if the password is too short, ornull
otherwise.
Example:
// Inside the Form component
const isShortPassword = (value) => {
return value.length < MIN_PASS_LEN ? ErrorMsg.PASSWORD_SHORT : null;
};
Function: isWeakPassword
Description: This function checks if a given password is considered weak. It uses a regular expression to check if the password contains at least one number, one lowercase letter, and one uppercase letter. If it fails the check, it returns an error message indicating that the password is weak.
Parameters:
value
: The password to check.
Returns:
string
: An error message if the password is weak, ornull
otherwise.
Example:
// Inside the Form component
const isWeakPassword = (value) => {
return validPasswordPattern.test(value) ? null : ErrorMsg.PASSWORD_WEAK;
};
Important Considerations:
- Error Handling: Implement robust error handling for the
onValidate
function to gracefully handle potential exceptions or server errors. - Accessibility: Ensure that the form is accessible for users with disabilities by using ARIA attributes, appropriate keyboard navigation, and screen reader-friendly markup.
- Security: If handling sensitive data, implement appropriate security measures to protect user information, such as encryption and input validation.
- Customization: The
Form
component is highly customizable through props. You can customize the appearance, behavior, and validation rules to fit your specific needs.