1.0.0 • Published 4 years ago
@cbto/ts-validator v1.0.0
typescript-validation
installation
npm install --save @cbt/typescript-validation
usage
For Angular, define model Person
import { required, maxlength, BaseModel } from '@cbt/typesript-validation';
...
export class Person extends BaseModel {
// override this method
getAssignedFields(): string[] {
return ["fullname"];
}
@required("fullname is required") // error message
@maxlength(10, "max length of full name is 10")
fullname: string;
}
In component
...
class CreatePersonComponent implements OnInit {
form: Person;
errorMessagesWithKey: any = {};
ngOnInit() {
this.initForm();
}
private initForm(): void {
this.form = new Person();
}
onFormChange() {
this.errorsWithKey = this.form.getErrorMessagesWithKey();
}
onFormSubmit() {
if (this.form.isValid()) {
// ...
} else {
// ...
}
}
}
In template of create person component
<form (change)="onFormChange()" (submit)="onFormSubmit()">
<!-- ... -->
<input type="text" name="fullname" [(ngModel)]="form.fullname" />
<button type="submit">submit</button>
<!-- ... -->
</form>
common issues
1.0.0
4 years ago