Package Exports
- @miyax/validatorjs
- @miyax/validatorjs/array
- @miyax/validatorjs/contextual
- @miyax/validatorjs/core
- @miyax/validatorjs/date
- @miyax/validatorjs/file
- @miyax/validatorjs/number
- @miyax/validatorjs/string
- @miyax/validatorjs/utility
Readme
π Leer en EspaΓ±ol
@miyax/validatorjs
A powerful and flexible JavaScript validation library inspired by Laravel Validation Rules.
π¦ Installation
npm install @miyax/validatorjs
yarn add @miyax/validatorjs
π Usage Example
import { validate } from '@miyax/validatorjs';
// Form data
const userData = {
name: 'John Doe',
email: 'john@example.com',
age: 28,
password: 'myPassword123'
};
// Validation rules
const rules = {
name: 'required|string|min:2|max:50',
email: 'required|email',
age: 'required|numeric|min:18|max:99',
password: 'required|string|min:8'
};
// Validate
const result = validate(userData, rules);
if (result.valid) {
console.log('β
Valid user');
} else {
console.log('β Errors found:');
result.errors.forEach(error => {
console.log(` β’ ${error.field}: ${error.message}`);
});
}
π Implemented Rules
String Rules
alpha
- Letters only (a-zA-Z)alpha_num
- Letters and numbersalpha_dash
- Letters, numbers, hyphens and underscoresascii
- ASCII characters onlyemail
- Valid emailjson
- Valid JSONlowercase
- Lowercase onlyuppercase
- Uppercase onlystring
- Must be stringurl
- Valid URLuuid
- Valid UUIDhex_color
- Hexadecimal colorstarts_with:value
- Starts with valueends_with:value
- Ends with valuedoesnt_start_with:value
- Doesn't start with valuedoesnt_end_with:value
- Doesn't end with valueregex:pattern
- Matches regular expressionnot_regex:pattern
- Doesn't match regular expression
Numeric Rules
numeric
- Valid numberinteger
- Integer numberdecimal:min,max
- Decimals (min-max places)digits:value
- Exactly N digitsdigits_between:min,max
- Between min and max digitsmin_digits:value
- Minimum N digitsmax_digits:value
- Maximum N digitsmultiple_of:value
- Multiple of valuegreater_than:value
- Greater than valuegreater_than_or_equal:value
- Greater than or equal to valueless_than:value
- Less than valueless_than_or_equal:value
- Less than or equal to value
Array Rules
array
- Must be arraydistinct
- Unique elementscontains:value
- Contains valuedoesnt_contain:value
- Doesn't contain valuein_array:field
- Value is in field arrayin:val1,val2,val3
- Value is in listnot_in:val1,val2,val3
- Value is not in list
Date Rules
date
- Valid datedate_format:format
- Specific date formatbefore:date
- Before datebefore_or_equal:date
- Before or equal to dateafter:date
- After dateafter_or_equal:date
- After or equal to datedate_equals:date
- Equal to datetimezone
- Valid timezone
File Rules
file
- Must be fileimage
- Must be imagemimes:jpg,png
- Allowed MIME typesmimetypes:image/*
- Allowed MIME categoriesextensions:jpg,png
- Allowed extensionsdimensions
- Image dimensions validation
Contextual Rules
min:value
- Minimum value/sizemax:value
- Maximum value/sizebetween:min,max
- Between two values/sizessize:value
- Exact sizesame:field
- Same as another fielddifferent:field
- Different from another field
Utility Rules
required
- Required fieldrequired_if:field,value
- Required if another field has valuefilled
- Not empty (if present)nullable
- Allows null valuesboolean
- Boolean valuepresent
- Must be presentpresent_if:field,value
- Present if another field has valuemissing
- Must not be presentmissing_if:field,value
- Missing if another field has valuesometimes
- Validate only if present
Validator
Class
import { Validator } from '@miyax/validatorjs/core';
const validator = new Validator();
// Available methods
validator.validate(data, rules, options);
validator.addRule(name, validatorFn, message);
validator.setMessages(messages);
validator.passes(data, rules);
validator.fails(data, rules);
createValidator()
Helper
import { createValidator } from '@miyax/validatorjs';
const validator = createValidator();
// Equivalent to: new Validator()
π Framework Examples
React
import React, { useState } from 'react';
import { validate } from '@miyax/validatorjs';
function ContactForm() {
const [formData, setFormData] = useState({
name: '',
email: '',
message: ''
});
const [errors, setErrors] = useState({});
const handleSubmit = (e) => {
e.preventDefault();
const rules = {
name: 'required|string|min:2',
email: 'required|email',
message: 'required|string|min:10'
};
const result = validate(formData, rules);
if (result.valid) {
// Submit form
console.log('Submitting...', formData);
setErrors({});
} else {
// Show errors
const errorMap = {};
result.errors.forEach(error => {
errorMap[error.field] = error.message;
});
setErrors(errorMap);
}
};
return (
<form onSubmit={handleSubmit}>
<input
type="text"
placeholder="Name"
value={formData.name}
onChange={(e) => setFormData({...formData, name: e.target.value})}
/>
{errors.name && <span className="error">{errors.name}</span>}
{/* More fields... */}
<button type="submit">Submit</button>
</form>
);
}
Vue 3
<template>
<form @submit.prevent="handleSubmit">
<input
v-model="form.email"
type="email"
placeholder="Email"
:class="{ error: errors.email }"
/>
<span v-if="errors.email" class="error-text">{{ errors.email }}</span>
<button type="submit">Submit</button>
</form>
</template>
<script setup>
import { ref, reactive } from 'vue';
import { validate } from '@miyax/validatorjs';
const form = reactive({
email: '',
password: ''
});
const errors = ref({});
const handleSubmit = () => {
const rules = {
email: 'required|email',
password: 'required|string|min:8'
};
const result = validate(form, rules);
if (result.valid) {
// Process form
console.log('Valid form');
errors.value = {};
} else {
// Show errors
errors.value = result.errors.reduce((acc, error) => {
acc[error.field] = error.message;
return acc;
}, {});
}
};
</script>
π€ FAQ
How to add Spanish messages?
import { Validator } from '@miyax/validatorjs';
const validator = new Validator();
validator.setMessages({
required: 'The :attribute field is required',
email: 'The :attribute field must be a valid email',
min: 'The :attribute field must have at least :param characters',
max: 'The :attribute field cannot have more than :param characters'
});
How to validate nested forms?
import { validate } from '@miyax/validatorjs';
// Complete example with nested object validation
const formData = {
personal: {
firstName: 'John',
lastName: 'Doe',
contact: {
email: 'john@example.com',
phone: '+1234567890'
}
},
preferences: {
newsletter: true,
theme: 'dark'
}
};
const rules = {
'personal.firstName': 'required|string|min:2',
'personal.lastName': 'required|string|min:2',
'personal.contact.email': 'required|email',
'personal.contact.phone': 'required|string|min:9',
'preferences.newsletter': 'required|boolean',
'preferences.theme': 'required|in:light,dark,auto'
};
const result = validate(formData, rules);
// The result will include specific errors with full paths
if (!result.valid) {
result.errors.forEach(error => {
console.log(`Error in ${error.field}: ${error.message}`);
});
}
Does it work with async/await?
async function validateAsync(data, rules) {
// Validation is synchronous, but you can use it in async context
const result = validate(data, rules);
if (result.valid) {
// Continue with async operations
await saveToDatabase(data);
}
return result;
}
π€ Contributing
Contributions are welcome!
- Fork the project
- Create a branch:
git checkout -b feature/new-rule
- Commit:
git commit -m 'Add new validation rule'
- Push:
git push origin feature/new-rule
- Open a Pull Request
π Made with β€οΈ for the JavaScript community!