Skip to content

Form Validation

The API provides powerful form validation functions that help developers ensure the correctness and completeness of user input. These methods cover overall form validation, field-level validation, rule updates, and more.

Validate Form

The validate method validates the entire form and returns the validation result in a callback. This method returns a Promise that resolves if validation passes, otherwise it rejects.

typescript
type validate = (callback:(...args:any[]) => void)=> Promise
  • Example:
js
fApi.validate((valid, fail) => {
  if (valid === true) {
    console.log('Form validation passed');
  } else {
    console.log('Form validation failed');
  }
}).then(() => {
    //Recommended
  console.log('Promise resolved: Form validation passed');
}).catch(() => {
  console.log('Promise rejected: Form validation failed');
});

Validate Specified Field

The validateField method validates a specified field and returns the validation result in a callback. This method returns a Promise that resolves if validation passes, otherwise it rejects.

typescript
type validateField = (field, callback:(...args:any[]) => void)=> Promise
  • Example:
js
fApi.validateField('goods_name', (valid, fail) => {
  if (valid === true) {
    console.log('Field validation passed');
    // todo Processing logic after field validation passes
  } else {
    console.log('Field validation failed');
    // todo Processing logic when field validation fails
  }
}).then(() => {
    //Recommended
  console.log('Promise resolved: Field validation passed');
}).catch(() => {
  console.log('Promise rejected: Field validation failed');
});

Update Validation Rules

The updateValidate method updates validation rules for the specified field. You can choose to overwrite or merge the existing rules.

typescript
interface updateValidate{
    //Overwrite update
    (field:string, validate:Object[]):void
    //Merge update
    (field:string, validate:Object[], merge:true):void
}
  • Example:
js
// Merge update validation rules of goods_name field
fApi.updateValidate('goods_name', [{ required: true }], true);
// Overwrite update validation rules of goods_name field
fApi.updateValidate('goods_name', [{ required: true }]);

The updateValidates method batch updates validation rules for multiple fields. You can choose to overwrite or merge the existing rules.

typescript
interface updateValidates{
    //Overwrite update
    (validates:{[field:string]: Object[]}):void
    //Merge update
    (validates:{[field:string]: Object[]}, merge:true):void
}
  • Example:
js
// Merge update validation rules of multiple fields
fApi.updateValidates({
  'goods_name': [{ required: false }],
  'price': [{ required: true, type: 'number' }]
}, true);
// Overwrite update validation rules of multiple fields
fApi.updateValidates({
  'goods_name': [{ required: true }],
  'price': [{ required: true, type: 'number' }]
});

Refresh Validation Rules

The refreshValidate method is used to manually refresh validation rules of the form. If validation rules are modified but not taking effect, you can call this method to ensure the rules take effect.

typescript
type refreshValidate = ()=>void
  • Example:
js
fApi.refreshValidate();
console.log('Validation rules have been refreshed');

Clear Form Validation State

The clearValidateState method is used to clear validation state of the form or specified fields.

typescript
interface clearValidateState {
    ():void
    (field:string, clearSub?:boolean):void
    (field:string[], clearSub?:boolean):void
}
  • Example:
js
// Clear validation state of entire form
fApi.clearValidateState();
// Clear validation state of single field
fApi.clearValidateState('goods_name');
// Clear validation state of multiple fields
fApi.clearValidateState(['goods_name', 'price']);

Clear Sub-Form Validation State

The clearSubValidateState method is used to clear validation state of sub-forms such as group, object, etc.

typescript
interface clearSubValidateState {
    (field:string):void
    (field:string[]):void
}
  • Example:
js
// Clear validation state of single sub-form
fApi.clearSubValidateState('goods_name');
// Clear validation state of multiple sub-forms
fApi.clearSubValidateState(['goods_name', 'price']);

Examples

Dynamically Update Validation Rules of Form Fields

In a registration form, users can choose different registration methods (such as email or phone number). Based on the user's selection, dynamically update validation rules of corresponding fields.

js
const registerMethod = fApi.getValue('register_method');
if (registerMethod === 'email') {
    fApi.updateValidate('email', [{ required: true, type: 'email', message: 'Please enter a valid email address' }]);
    fApi.updateValidate('phone', [{ required: false }]);
} else {
    fApi.updateValidate('phone', [{ required: true, pattern: /^\d{10}$/, message: 'Please enter a valid phone number' }]);
    fApi.updateValidate('email', [{ required: false }]);
}
fApi.refreshValidate(); // Refresh validation rules to apply changes

Batch Update Validation Rules of Multiple Fields

In a complex form, batch update validation rules of multiple fields based on user role. For example, administrators need more required fields, while regular users only need to fill in basic information.

js
const userRole = fApi.getValue('user_role');
if (userRole === 'admin') {
    fApi.updateValidates({
        'username': [{ required: true }],
        'email': [{ required: true, type: 'email' }],
        'permissions': [{ required: true }]
    });
} else {
    fApi.updateValidates({
        'username': [{ required: true }],
        'email': [{ required: true, type: 'email' }],
        'permissions': [{ required: false }]
    });
}
fApi.refreshValidate(); // Refresh validation rules to apply changes

Clear Form Validation State

In an edit form, after the user submits the form, if they want to continue editing, they need to clear validation state of all fields to re-validate.

js
fApi.submit().then(() => {
    console.log('Form submitted successfully');
    fApi.clearValidateState(); // Clear validation state after successful submission
});

Re-trigger Validation Logic Before Form Submission

In a multi-condition form, users may modify some validated fields. Before submission, you need to re-trigger validation logic to ensure all data conforms to the latest validation rules.

js
fApi.validate().then((state) => {
    if (state.valid) {
        fApi.submit();
    } else {
        console.error('Form validation failed');
    }
});

FormCreate is an open-source project released under the MIT License. Free for personal and commercial use.