other components... (2)
This commit is contained in:
15
src/modules/useFormValidation.ts
Normal file
15
src/modules/useFormValidation.ts
Normal file
@@ -0,0 +1,15 @@
|
||||
import { reactive } from '@vue/reactivity'
|
||||
import useValidators from '@/modules/validators'
|
||||
|
||||
const errors: any = reactive({})
|
||||
|
||||
export default function useFormValidation() {
|
||||
const { isEmpty, minLength, isEmail } = useValidators()
|
||||
const validateNameField = (fieldName: string, fieldValue: string) => {
|
||||
errors[fieldName] = !fieldValue ? isEmpty(fieldName, fieldValue) : minLength(fieldName, fieldValue, 4)
|
||||
}
|
||||
const validateEmailField = (fieldName: string, fieldValue: string) => {
|
||||
errors[fieldName] = !fieldValue ? isEmpty(fieldName, fieldValue) : isEmail(fieldName, fieldValue)
|
||||
}
|
||||
return { errors, validateNameField, validateEmailField }
|
||||
}
|
||||
16
src/modules/validators.ts
Normal file
16
src/modules/validators.ts
Normal file
@@ -0,0 +1,16 @@
|
||||
export default function useValidators() {
|
||||
|
||||
const isEmpty = (fieldName: string, fieldValue: string) => {
|
||||
return !fieldValue ? 'The ' + fieldName + ' field is required' : '';
|
||||
}
|
||||
|
||||
const minLength = (fieldName: string, fieldValue: string, min: number) => {
|
||||
return fieldValue.length < min ? `The ${fieldName} field must be atleast ${min} characters long` : '';
|
||||
}
|
||||
|
||||
const isEmail = (fieldName: string, fieldValue: string) => {
|
||||
let re = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
|
||||
return !re.test(fieldValue) ? 'The input is not a valid ' + fieldName + ' address' : '';
|
||||
}
|
||||
return { isEmpty, minLength, isEmail }
|
||||
}
|
||||
Reference in New Issue
Block a user