|
@@ -0,0 +1,62 @@
|
|
|
+interface IRuleField {
|
|
|
+ name: string
|
|
|
+ message: string
|
|
|
+ required?: boolean
|
|
|
+}
|
|
|
+
|
|
|
+type RuleMapType = {
|
|
|
+ [key: string]: {
|
|
|
+ message: string
|
|
|
+ required?: boolean
|
|
|
+ }
|
|
|
+}
|
|
|
+export class FormRequiredValidate {
|
|
|
+ private static ruleMap: RuleMapType = {}
|
|
|
+
|
|
|
+ static validate(rules: any[]) {
|
|
|
+ this.ruleMap = {}
|
|
|
+ for (const item of rules) {
|
|
|
+ if (item['name']) {
|
|
|
+ this.ruleMap[item['name']] = {
|
|
|
+ message: item['message'] || `${item['name']}不能为空!`,
|
|
|
+ required: item['required'] ?? true
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+ return (form: any, callback: (state: boolean, rule: IRuleField | null) => void) => {
|
|
|
+ let cRule: IRuleField | null = null
|
|
|
+ let state: boolean = true
|
|
|
+ for (let i: number = 0; i < rules.length; i++) {
|
|
|
+ const name = rules[i]['name']
|
|
|
+ console.log(name)
|
|
|
+ if (
|
|
|
+ Object.hasOwn(form, name) &&
|
|
|
+ this.ruleMap[name]['required'] &&
|
|
|
+ !this.isNotBlank(form[name])
|
|
|
+ ) {
|
|
|
+ cRule = {
|
|
|
+ name,
|
|
|
+ ...this.ruleMap[name]
|
|
|
+ }
|
|
|
+ state = false
|
|
|
+ break
|
|
|
+ }
|
|
|
+ }
|
|
|
+ callback && callback(state, cRule)
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ static isNotBlank(val: any): boolean {
|
|
|
+ if (val === null) return false
|
|
|
+ if (val === undefined) return false
|
|
|
+ if (typeof val === 'string') {
|
|
|
+ if (val.trim() === '') return false
|
|
|
+ } else if (val instanceof Array) {
|
|
|
+ if (val.length === 0) return false
|
|
|
+ } else if (val instanceof Object) {
|
|
|
+ const keys = Object.keys(val)
|
|
|
+ if (keys.length === 0) return false
|
|
|
+ }
|
|
|
+ return true
|
|
|
+ }
|
|
|
+}
|