CSS-only distribution of Semantic UI providing comprehensive styling and JavaScript behaviors for web applications
—
Comprehensive form validation system with built-in rules, custom validation support, and detailed error reporting for creating robust user input handling.
Complete form validation with field rules, error display, and submission handling.
/**
* Initialize form validation on elements
* @param settings - Configuration object for form validation behavior
*/
$('.ui.form').form(settings);
interface FormSettings {
// Validation
fields: { [fieldName: string]: FieldValidation }; // Field validation rules
rules: { [ruleName: string]: ValidationRule }; // Custom validation rules
prompts: { [ruleName: string]: string }; // Custom error messages
// Behavior
on: 'blur' | 'change' | 'submit'; // When to validate
revalidate: boolean; // Revalidate on input after error
delay: boolean; // Delay validation on input
inline: boolean; // Show errors inline with fields
transition: string; // Error message transition
duration: number; // Transition duration (ms)
// Display
keyboardShortcuts: boolean; // Enable keyboard shortcuts
// Callbacks
onValid: () => void; // When form becomes valid
onInvalid: () => void; // When form becomes invalid
onSuccess: (event: Event, fields: any) => void; // On successful validation
onFailure: (formErrors: string[], fields: any) => void; // On validation failure
}
interface FieldValidation {
identifier: string; // Field identifier
rules: ValidationRule[]; // Array of validation rules
optional?: boolean; // Field is optional
depends?: string; // Field depends on another field
}
interface ValidationRule {
type: string; // Rule type
prompt?: string; // Custom error message
value?: any; // Rule parameter value
}Form Methods:
// Validation
$('.ui.form').form('validate form');
$('.ui.form').form('validate field', identifier);
$('.ui.form').form('is valid');
$('.ui.form').form('is invalid');
// Error management
$('.ui.form').form('add errors', errors);
$('.ui.form').form('remove errors');
$('.ui.form').form('add field error', identifier, errors);
$('.ui.form').form('remove field error', identifier);
// Field values
$('.ui.form').form('get field', identifier);
$('.ui.form').form('get fields', identifiers);
$('.ui.form').form('get values');
$('.ui.form').form('set value', identifier, value);
$('.ui.form').form('set values', values);
// State management
$('.ui.form').form('submit');
$('.ui.form').form('reset');
$('.ui.form').form('clear');Built-in Validation Rules:
// Basic rules
{ type: 'empty', prompt: 'Please enter a value' }
{ type: 'length[6]', prompt: 'Must be at least 6 characters' }
{ type: 'minLength[2]', prompt: 'Must be at least 2 characters' }
{ type: 'maxLength[10]', prompt: 'Must be 10 characters or less' }
{ type: 'exactLength[5]', prompt: 'Must be exactly 5 characters' }
// Format validation
{ type: 'email', prompt: 'Please enter a valid email' }
{ type: 'url', prompt: 'Please enter a valid URL' }
{ type: 'regExp[/^[a-zA-Z]+$/]', prompt: 'Must contain only letters' }
// Numeric validation
{ type: 'integer', prompt: 'Must be an integer' }
{ type: 'decimal', prompt: 'Must be a decimal number' }
{ type: 'number', prompt: 'Must be a number' }
{ type: 'minValue[0]', prompt: 'Must be at least 0' }
{ type: 'maxValue[100]', prompt: 'Must be 100 or less' }
// Comparison rules
{ type: 'match[password]', prompt: 'Must match password field' }
{ type: 'different[username]', prompt: 'Must be different from username' }
{ type: 'creditCard', prompt: 'Must be a valid credit card number' }
// Selection rules
{ type: 'minCount[2]', prompt: 'Must select at least 2 options' }
{ type: 'exactCount[3]', prompt: 'Must select exactly 3 options' }
{ type: 'maxCount[5]', prompt: 'Must select 5 or fewer options' }
// Date validation
{ type: 'date', prompt: 'Must be a valid date' }
{ type: 'dateRange[mm/dd/yyyy..mm/dd/yyyy]', prompt: 'Must be in date range' }
// Conditional validation
{ type: 'checked', prompt: 'Must be checked' }
{ type: 'contains[value]', prompt: 'Must contain specified value' }
{ type: 'containsExactly[value]', prompt: 'Must contain exactly specified value' }
{ type: 'doesntContain[value]', prompt: 'Must not contain specified value' }Usage Examples:
<!-- Basic form validation -->
<form class="ui form">
<div class="field">
<label>Email</label>
<input type="email" name="email" placeholder="Enter your email">
</div>
<div class="field">
<label>Password</label>
<input type="password" name="password" placeholder="Enter password">
</div>
<div class="field">
<label>Confirm Password</label>
<input type="password" name="confirmPassword" placeholder="Confirm password">
</div>
<div class="ui submit button">Submit</div>
<div class="ui error message"></div>
</form>
<script>
$('.ui.form').form({
fields: {
email: {
identifier: 'email',
rules: [
{ type: 'empty', prompt: 'Please enter your email' },
{ type: 'email', prompt: 'Please enter a valid email' }
]
},
password: {
identifier: 'password',
rules: [
{ type: 'empty', prompt: 'Please enter a password' },
{ type: 'minLength[6]', prompt: 'Password must be at least 6 characters' }
]
},
confirmPassword: {
identifier: 'confirmPassword',
rules: [
{ type: 'empty', prompt: 'Please confirm your password' },
{ type: 'match[password]', prompt: 'Passwords must match' }
]
}
}
});
</script>Create custom validation rules for specific business logic requirements.
/**
* Add custom validation rule
* @param ruleName - Name of the custom rule
* @param ruleFunction - Function that performs validation
*/
$.fn.form.settings.rules[ruleName] = function(value, parameter) {
// Return true if valid, false if invalid
return boolean;
};
// Custom rule with parameter
$.fn.form.settings.rules.customRule = function(value, parameter) {
// parameter contains the value passed in brackets
return value.length >= parseInt(parameter);
};Custom Rule Examples:
// Phone number validation
$.fn.form.settings.rules.phone = function(value) {
return /^\d{3}-\d{3}-\d{4}$/.test(value);
};
// Strong password validation
$.fn.form.settings.rules.strongPassword = function(value) {
return /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]/.test(value);
};
// Age validation
$.fn.form.settings.rules.validAge = function(value, range) {
var age = parseInt(value);
var [min, max] = range.split('-').map(n => parseInt(n));
return age >= min && age <= max;
};
// Usage in form validation
$('.ui.form').form({
fields: {
phone: {
identifier: 'phone',
rules: [
{ type: 'phone', prompt: 'Please enter a valid phone number (XXX-XXX-XXXX)' }
]
},
password: {
identifier: 'password',
rules: [
{ type: 'strongPassword', prompt: 'Password must contain uppercase, lowercase, number and special character' }
]
},
age: {
identifier: 'age',
rules: [
{ type: 'validAge[18-120]', prompt: 'Age must be between 18 and 120' }
]
}
}
});Implement conditional validation based on other field values or form state.
// Conditional field validation
{
identifier: 'fieldName',
depends: 'otherField', // Only validate if other field has value
rules: [
{ type: 'empty', prompt: 'This field is required when other field is filled' }
]
}
// Custom conditional validation
$.fn.form.settings.rules.conditionalRequired = function(value, parameter) {
var dependentFieldValue = $('[name="' + parameter + '"]').val();
if (dependentFieldValue) {
return value.length > 0;
}
return true; // Not required if dependent field is empty
};Conditional Validation Examples:
<!-- Conditional validation form -->
<form class="ui form">
<div class="field">
<label>Account Type</label>
<select name="accountType" class="ui dropdown">
<option value="">Select Type</option>
<option value="business">Business</option>
<option value="personal">Personal</option>
</select>
</div>
<div class="field">
<label>Company Name</label>
<input type="text" name="companyName" placeholder="Required for business accounts">
</div>
<div class="field">
<label>Tax ID</label>
<input type="text" name="taxId" placeholder="Required for business accounts">
</div>
</form>
<script>
// Custom conditional rule
$.fn.form.settings.rules.requiredForBusiness = function(value) {
var accountType = $('[name="accountType"]').val();
if (accountType === 'business') {
return value.length > 0;
}
return true;
};
$('.ui.form').form({
fields: {
accountType: {
identifier: 'accountType',
rules: [
{ type: 'empty', prompt: 'Please select account type' }
]
},
companyName: {
identifier: 'companyName',
rules: [
{ type: 'requiredForBusiness', prompt: 'Company name is required for business accounts' }
]
},
taxId: {
identifier: 'taxId',
rules: [
{ type: 'requiredForBusiness', prompt: 'Tax ID is required for business accounts' }
]
}
}
});
</script>Real-time validation with inline error display for individual fields.
// Form with inline validation
$('.ui.form').form({
inline: true, // Enable inline validation
on: 'blur', // Validate on field blur
revalidate: true, // Revalidate on input after error
fields: {
email: {
identifier: 'email',
rules: [
{ type: 'email', prompt: 'Enter a valid email address' }
]
}
}
});Real-time Validation Example:
<!-- Form with inline validation -->
<form class="ui form">
<div class="field">
<label>Username</label>
<input type="text" name="username" placeholder="Choose a username">
</div>
<div class="field">
<label>Email</label>
<input type="email" name="email" placeholder="Enter your email">
</div>
<div class="ui submit button">Register</div>
</form>
<script>
$('.ui.form').form({
inline: true,
on: 'blur',
revalidate: true,
fields: {
username: {
identifier: 'username',
rules: [
{ type: 'empty', prompt: 'Username is required' },
{ type: 'minLength[3]', prompt: 'Username must be at least 3 characters' },
{ type: 'regExp[/^[a-zA-Z0-9_]+$/]', prompt: 'Username can only contain letters, numbers, and underscores' }
]
},
email: {
identifier: 'email',
rules: [
{ type: 'empty', prompt: 'Email is required' },
{ type: 'email', prompt: 'Please enter a valid email address' }
]
}
},
onSuccess: function(event, fields) {
console.log('Form submitted successfully', fields);
return false; // Prevent actual form submission for demo
}
});
</script>Customize error messages for better user experience:
prompts: {
empty: '{name} is required',
email: '{name} must be a valid email address',
minLength: '{name} must be at least {ruleValue} characters'
}Set up field dependencies for conditional validation:
{
identifier: 'confirmEmail',
depends: 'email',
rules: [
{ type: 'match[email]', prompt: 'Email addresses must match' }
]
}Implement server-side validation checks:
$.fn.form.settings.rules.uniqueUsername = function(value, identifier, $module) {
var isValid = false;
$.ajax({
url: '/check-username',
data: { username: value },
async: false,
success: function(response) {
isValid = response.available;
}
});
return isValid;
};Install with Tessl CLI
npx tessl i tessl/npm-semantic-ui-css