In index.html we have
<form>
<input type="text" placeholder="Course Title" id="title" />
<input type="text" placeholder="Price" id="price" />
<button type="submit">Submit</button>
</form>
and inside our ts (transpiled into js file and link it into our index.html), we write:
enum Validation {
required = "required",
positive = "positive"
}
interface ValidatorConfig {
[property: string]: {
[validatableProp: string]: Validation[]; //e.g., [Validation.required, Validation.positive]
};
}
const registeredValidators: ValidatorConfig = {};
function Required(target: any, propName: string) {
//we don't have propertyDescriptor for property, it exists only for methods
registeredValidators[target.constructor.name] = {
...registeredValidators[target.constructor.name],
[propName]: [Validation.required]
};
}
function Positive(target: any, propName: string) {
registeredValidators[target.constructor.name] = {
...registeredValidators[target.constructor.name],
[propName]: [Validation.positive]
};
}
function validate(obj: any) {
const objValidatorConfig = registeredValidators[obj.constructor.name];
if (!objValidatorConfig) {
return true;
} else {
let validated = true;
for (const prop in objValidatorConfig) {
for (const validator of objValidatorConfig[prop]) {
if (validator === (Validation.required as string)) {
console.log("run?");
validated = validated && obj[prop].trim().length > 0;
}
if (validator === (Validation.positive as string)) {
validated = validated && obj[prop] > 0;
}
}
}
return validated;
}
}
class Course {
@Required
public title: string;
@Positive
public price: number;
constructor(t: string, p: number) {
this.title = t;
this.price = p;
}
}
const courseForm = document.querySelector("form")!;
courseForm.addEventListener("submit", e => {
e.preventDefault();
const titleEl = document.getElementById("title") as HTMLInputElement;
const priceEl = document.getElementById("price") as HTMLInputElement;
const title = titleEl.value;
const price = +priceEl.value;
const newCourse = new Course(title, price);
if (!validate(newCourse)) {
alert("Invalid input, please try again!");
return;
}
console.log(newCourse);
});
No comments:
Post a Comment