Skip to content

Instantly share code, notes, and snippets.

@vahidid
Last active February 25, 2022 10:26
Show Gist options
  • Save vahidid/492b5d563f2f93d859d0c883a799e7c4 to your computer and use it in GitHub Desktop.
Save vahidid/492b5d563f2f93d859d0c883a799e7c4 to your computer and use it in GitHub Desktop.
Validate object in typescript
import { NumberFormatValues } from 'react-number-format'
import i18n from '../Config/i18n'
export function validateEmail(email: string): RegExpExecArray | null {
const isEmail = /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,6}$/.exec(
email
)
return isEmail
}
export function validateMobile(mobile: string): RegExpExecArray | null {
const isMobile =
/^[+]?[(]?[0-9]{3}[)]?[-\s.]?[0-9]{3}[-\s.]?[0-9]{4,6}$/.exec(mobile)
return isMobile
}
interface IValidateObject {
[key: string]: string // like => "required|min:3|max:10"
}
export async function Validate(
// eslint-disable-next-line @typescript-eslint/no-explicit-any
obj: any,
rules: IValidateObject
): Promise<void> {
Object.keys(rules).forEach((key) => {
const rule = rules[key].split('|')
rule.forEach((r) => {
const [ruleName, ruleValue] = r.split(':')
const value = obj[key]
switch (ruleName) {
case 'required':
if (!value || value.length === 0) {
throw new Error(
i18n.t('validation.required', { key: i18n.t(key) })
)
}
break
case 'required_if': {
const [subRuleName, subRuleValue] = ruleValue.split(',')
if (obj[subRuleName] === subRuleValue) {
throw new Error(
i18n.t('validation.required', {
key: i18n.t(key),
max: ruleValue,
})
)
}
break
}
case 'min':
if (value.length < ruleValue) {
throw new Error(
i18n.t('validation.min', {
key: i18n.t(key),
min: ruleValue,
})
)
}
break
case 'max':
if (value.length > ruleValue) {
throw new Error(
i18n.t('validation.max', {
key: i18n.t(key),
max: ruleValue,
})
)
}
break
case 'email':
if (!validateEmail(value)) {
throw new Error(
i18n.t('validation.invalid', { key: i18n.t(key) })
)
}
break
case 'mobile':
if (!validateMobile(value)) {
throw new Error(
i18n.t('validation.invalid', { key: i18n.t(key) })
)
}
break
case 'number':
if (typeof value !== 'number') {
throw new Error(
i18n.t('validation.invalid', {
key: i18n.t(key),
})
)
}
break
default:
throw new Error(
i18n.t('validation.invalid', {
key: i18n.t(key),
})
)
break
}
})
})
}
export function numberInputAllowed(
values: NumberFormatValues,
allowed: number
): boolean {
const { floatValue } = values
return floatValue ? floatValue <= allowed : true
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment