Skip to content

Commit

Permalink
再利用可能なバリデーション機能
Browse files Browse the repository at this point in the history
  • Loading branch information
s-yoshiii committed Apr 26, 2022
1 parent 8a7285e commit 6bec5c4
Showing 1 changed file with 63 additions and 3 deletions.
66 changes: 63 additions & 3 deletions src/app.ts
@@ -1,3 +1,46 @@
//validate
interface Validatable {
value: string | number;
required?: boolean;
minLength?: number;
maxLength?: number;
min?: number;
max?: number;
}
function validate(validatableInput: Validatable) {
let isValid = true;
if (validatableInput.required) {
isValid = isValid && validatableInput.value.toString().trim().length !== 0;
}
if (
validatableInput.minLength != null &&
typeof validatableInput.value === "string"
) {
isValid =
isValid && validatableInput.value.length >= validatableInput.minLength;
}
if (
validatableInput.maxLength != null &&
typeof validatableInput.value === "string"
) {
isValid =
isValid && validatableInput.value.length <= validatableInput.maxLength;
}
if (
validatableInput.min != null &&
typeof validatableInput.value === "number"
) {
isValid = isValid && validatableInput.value >= validatableInput.min;
}
if (
validatableInput.max != null &&
typeof validatableInput.value === "number"
) {
isValid = isValid && validatableInput.value <= validatableInput.max;
}
return isValid;
}

// autobind decorator
function autobind(
_target: any,
Expand Down Expand Up @@ -49,10 +92,26 @@ class ProjectInput {
const enterdTitle = this.titleInputElement.value;
const enterdDescription = this.descriptionInputElement.value;
const enterdManday = this.mandayInputElement.value;

const titleValidatable: Validatable = {
value: enterdTitle,
required: true,
};
const descriptionValidatable: Validatable = {
value: enterdDescription,
required: true,
minLength: 5,
};
const mandayValidatable: Validatable = {
value: +enterdManday,
required: true,
min: 1,
max: 1000,
};
if (
enterdTitle.trim().length === 0 ||
enterdDescription.trim().length === 0 ||
enterdManday.trim().length === 0
!validate(titleValidatable) ||
!validate(descriptionValidatable) ||
!validate(mandayValidatable)
) {
alert("入力値が正しく有りません。再度お試しください。");
return;
Expand All @@ -71,6 +130,7 @@ class ProjectInput {
const userInput = this.gatherUserInput();
if (Array.isArray(userInput)) {
const [title, desc, manday] = userInput;
console.log([title, desc, manday]);
alert([title, desc, manday]);
this.clearInputs();
}
Expand Down

0 comments on commit 6bec5c4

Please sign in to comment.