Napisałem aplikację w Vue.js. Zmodyfikuj kod, aby zamiast… · The Chat Archive
Explore / Programming Napisałem aplikację w Vue.js. Zmodyfikuj kod, aby zamiast używać const nameRules =… Save Share Download ▾ ReportNapisałem aplikację w Vue.js. Zmodyfikuj kod, aby zamiast używać
code Copy code
const nameRules = RulesUtils.MandatoryString(128);
const ipAddressRules = [
v => /^(25[0-5]|2[0-4]\d|[01]?\d\d?)\.(25[0-5]|2[0-4]\d|[01]?\d\d?)\.(25[0-5]|2[0-4]\d|[01]?\d\d?)\.(25[0-5]|2[0-4]\d|[01]?\d\d?)$/.test(v) || "Niepoprawny adres IP"
];
wykorzystać rules-utils.ts.
/// printer-posnet-card.vue
code Copy code
<v-row dense>
<v-col cols="12" sm="6">
<v2-text-field
v-model="model.ipAddress"
:rules="ipAddressRules"
:readonly="readonly"
class="mb-2"
label="Adres IP" />
</v-col>
<v-col cols="12" sm="6">
<printer-posnet-target-selector v-model="model.targetId" />
</v-col>
</v-row>
<v-row dense>
<v-col cols="12" sm="6" class="d-flex align-center">
<v-switch
v-model="model.isActive"
:disabled="readonly"
label="Aktywny"
class="ma-0" />
</v-col>
<v-col cols="12" sm="6">
<organization-unit-selector
v-model="model.organizationUnitId"
:rules="organizationUnitIdRules"
:readonly="readonly"
label="Jednostka Organizacyjna"
required />
</v-col>
</v-row>
<v-row justify="end">
<v-col cols="auto">
<submit-discard-async-buttons :submit="submit" @discard="discard" />
</v-col>
</v-row>
</v2-form>
</loading-container>
/// rules-utils.ts
import ValidatePolish from "@/lib/validate-polish";
import Util from "@/lib/util";
export class RulesUtils {
public static NotEmpty = [v => !!v || "Pole wymagane"];
public static NotEmptyAllowZero = [v => v === 0 || !!v || "Pole wymagane"];
public static NotEmptyArray = [v => (!!v && v.length > 0) || "Pole wymagane"];
Show full message · 384 lines Assistant2024-10-10 13:31 UTC Copy response
Copy first prompt
Details
Provider OpenAI
Model provenance As recorded by source dataset
Turns 1 (2 messages)
Language pl
Conversation date Oct 10, 2024
Added to archive Nov 16, 2026
ID 01m7h41x6f9t60p72nn39hv0yaSource & license Imported from WildChat-4.8M (AI2) (source ). Imported records earn no Research Points.
Upstream record: 271ee775184a3bd4df7c7a643e75e995
Zhao et al., WildChat: 1M ChatGPT Interaction Logs in the Wild (ICLR 2024). Contains information from WildChat-4.8M, made available under the ODC Attribution License.
License: ODC-BY-1.0
public static OptionalPrice = [
v =>
v === null ||
(ValidatePolish.amount(v) && Number(v) >= 0 && Number(v) < 100000) ||
"Niepoprawna wartość"
];
public static Price = [
v => (v !== "" && v !== null) || "Pole jest wymagane",
...RulesUtils.OptionalPrice
];
public static OptionalEmail = [
v => !v || (!!v && ValidatePolish.email(v)) || "Niepoprawny adres e-mail"
];
public static MandatoryEmail = [
v => (!!v && ValidatePolish.email(v)) || "Niepoprawny adres e-mail"
];
public static OptionalPhoneNumber = [
v => !v || (!!v && ValidatePolish.phoneNumber(v)) || "Niepoprawny numer telefonu"
];
public static MandatoryPesel = [
...RulesUtils.NotEmpty,
v => !v || (!!v && ValidatePolish.pesel(v)) || "Niepoprawny numer Pesel"
];
public static OptionalPesel = [
v => !v || (!!v && ValidatePolish.pesel(v)) || "Niepoprawny numer Pesel"
];
public static OptionalRegon = [
v =>
!v ||
(!!v &&
(v.length === 7 || v.length === 9 || v.length === 14) &&
Number.isInteger(Number(v))) ||
"Niepoprawny Regon"
];
public static RequiredRegon = [v => !!v || "Pole wymagane", ...RulesUtils.OptionalRegon];
public static NonNullNumber() {
return [v => !!v || v === 0 || "Wartość nie może byś pusta"];
}
public static IntegerNumber() {
return [v => (!v && v !== 0) || Number.isInteger(Number(v)) || "Wartość musi być całkowita"];
}
public static MinNumber(min: number) {
return [
v => (!v && v !== 0) || Number(v) >= min || Wartość musi być więsza bądź równa ${min}
];
}
public static MaxNumber(max: number) {
return [
v => (!v && v !== 0) || Number(v) <= max || Wartość musi być mniejsza bądź równa ${max}
];
}
public static OptionalInteger(min: number, max: number) {
return [
...RulesUtils.IntegerNumber(),
...RulesUtils.MinNumber(min),
...RulesUtils.MaxNumber(max)
];
}
public static MandatoryInteger(min: number, max: number) {
return [...RulesUtils.NonNullNumber(), ...RulesUtils.OptionalInteger(min, max)];
}
public static MandatoryString(maxChars: number, minChars?: number) {
const minCharsRules = minChars
? [v => !v || v.length >= minChars || Pole musi mieć przynajmniej ${minChars} znaki]
: [];
return [
v => !!v || "Pole wymagane",
v => (!!v && v.length >= 0) || "Pusta wartość",
v => (!!v && v.length >= 0 && v.length < maxChars) || "Nazwa za długa",
...minCharsRules
];
}
public static OptionalString(maxChars: number, minChars?: number) {
const minCharsRules = minChars
? [v => !v || v.length >= minChars || Pole musi mieć przynajmniej ${minChars} znaki]
: [];
return [
v => !v || (!!v && v.length >= 0 && v.length < maxChars) || "Nazwa za długa",
...minCharsRules
];
}
public static PostalCode() {
return [v => (!!v && /^[0-9]{2}-[0-9]{3}$/.test(v)) || "Niepoprawny kod pocztowy"];
}
public static ExcludedHtmlControlSequences() {
return RulesUtils.ExcludedStrings([""]);
}
public static ExcludedStrings(vals: string[]) {
return vals.map(
exV => v => !${v}.includes(exV) || Tekst zawiera niedozwolone sekwencje znaków: ${exV}
);
}
public static isValidPercent(v: any) {
return Number.isInteger(Number(v * 100)) && Number(v) >= 0 && Number(v) <= 100;
}
public static isValidAmount(v: any, max: number) {
return ValidatePolish.amount(v) && Number(v) >= 0 && Number(v) < max;
}
public static OptionalPercentRules = [
v => (!v && v !== 0) || RulesUtils.isValidPercent(v) || "Niepoprawna wartość"
];
public static OptionalAmountRules(max?: number) {
return [
v => (!v && v !== 0) || RulesUtils.isValidAmount(v, max || 100000) || "Niepoprawna wartość"
];
}
public static MandatoryPercentRules = [
v => v !== "" || "Pole jest wymagane",
v => RulesUtils.isValidPercent(v) || "Niepoprawna wartość"
];
public static MandatoryAmountRules(max?: number) {
return [
v => v !== "" || "Pole jest wymagane",
v => RulesUtils.isValidAmount(v, max || 100000) || "Niepoprawna wartość"
];
}
public static MandatoryFile(maxSize: number) {
return [
v => {
if (!v) return "Pole obowiązkowe";
if (v.size > maxSize) {
return Załączony plik musi mieć rozmiar mniejszy od ${Util.formatBytes( maxSize )};
}
return true;
}
];
}
public static optionalBankAccount = [
v => !v || (!!v && RulesUtils.isBankAccountValid(v)) || "Podaj prawidłowy numer konta bankowego"
];
public static mandatoryBankAccount = [
...RulesUtils.NotEmpty,
...RulesUtils.optionalBankAccount
];
private static isBankAccountValid(nrb: string) {
nrb = nrb.replace(/[^0-9]+/g, "");
const weights = [
1, 10, 3, 30, 9, 90, 27, 76, 81, 34, 49, 5, 50, 15, 53, 45, 62, 38, 89, 17, 73, 51, 25, 56,
75, 71, 31, 19, 93, 57
];
code Copy code
if (nrb.length !== 26) {
return false;
}
nrb = nrb + "2521";
nrb = nrb.substring(2) + nrb.substring(0, 2);
let Z = 0;
for (let i = 0; i < 30; i++) {
Z += parseInt(nrb[29 - i]) * weights[i];
}
return Z % 97 === 1;
Aby zoptymalizować kod Twojej aplikacji Vue.js i wykorzystać rules-utils.ts do walidacji zarówno pola name, jak i ipAddress, wykonaj następujące kroki:
Rozszerz rules-utils.ts o regułę walidacji adresu IP.
Zaktualizuj komponent PrinterPosnetCard.vue, aby używał nowej reguły z RulesUtils.
Poniżej przedstawiam szczegółowe instrukcje oraz przykładowy kod.
1. Rozszerzenie rules-utils.ts o regułę walidacji adresu IP
Najpierw dodaj nową statyczną metodę do klasy RulesUtils, która będzie zawierała regułę walidacji adresu IP. Możesz nazwać ją na przykład IPAddress.
rules-utils.ts :
typescript Copy code
import ValidatePolish from "@/lib/validate-polish";
import Util from "@/lib/util";
export class RulesUtils {
// ... istniejące reguły ...
public static IPAddress = [
v =>
/^(25[0-5]|2[0-4]\d|[01]?\d\d?)\.(25[0-5]|2[0-4]\d|[01]?\d\d?)\.(25[0-5]|2[0-4]\d|[01]?\d\d?)\.(25[0-5]|2[0-4]\d|[01]?\d\d?)$/.test(v) ||
"Niepoprawny adres IP"
];
// Opcjonalnie, jeśli chcesz mieć walidację opcjonalnego adresu IP:
public static OptionalIPAddress = [
v => !v || /^(25[0-5]|2[0-4]\d|[01]?\d\d?)\.(25[0-5]|2[0-4]\d|[01]?\d\d?)\.(25[0-5]|2[0-4]\d|[01]?\d\d?)\.(25[0-5]|2[0-4]\d|[01]?\d\d?)$/.test(v) ||
"Niepoprawny adres IP"
];
}
Wyjaśnienie:
Dodaliśmy nową statyczną właściwość IPAddress, która zawiera tablicę reguł walidacji.
Reguła używa wyrażenia regularnego, które sprawdza poprawność adresu IPv4.
Możesz również dodać OptionalIPAddress, jeśli chcesz, aby pole mogło być opcjonalne, ale jeśli jest wypełnione, musi być poprawne.
2. Aktualizacja komponentu PrinterPosnetCard.vue
Teraz zaktualizuj komponent Vue, aby używał nowej reguły RulesUtils.IPAddress zamiast definiować regułę inline.
PrinterPosnetCard.vue :
Wyjaśnienie:
Import RulesUtils:
Upewnij się, że RulesUtils jest zaimportowany z odpowiedniej ścieżki.
Definicja ipAddressRules:
Zamiast definiować ipAddressRules bezpośrednio w komponencie za pomocą wyrażenia regularnego, teraz przypisujemy je do RulesUtils.IPAddress. Dzięki temu centralizujesz logikę walidacji i ułatwiasz ponowne użycie reguł w innych komponentach.
Zastosowanie reguł w szablonie:
W szablonie (<template>) komponentu, pole Adres IP korzysta teraz z :rules="ipAddressRules", które jest dostarczane przez RulesUtils.
Dodatkowe Uwagi
Modularność i Reużywalność:
Przeniesienie reguł walidacji do rules-utils.ts poprawia modularność kodu oraz ułatwia konserwację i reużycie reguł w różnych miejscach aplikacji.
Rozszerzalność:
Jeśli w przyszłości będziesz potrzebować więcej reguł walidacyjnych (np. dla innych typów danych), możesz je łatwo dodać do RulesUtils i używać w komponentach bez konieczności powielania kodu.
Testowanie:
Centralne zarządzanie regułami ułatwia również testowanie walidacji, ponieważ wszystkie reguły są zdefiniowane w jednym miejscu.
Pełna Updated rules-utils.ts
Dla pełnej jasności, oto pełny zaktualizowany plik rules-utils.ts z dodaną regułą IPAddress:
rules-utils.ts :
Podsumowanie:
Dzięki tym zmianom Twój komponent PrinterPosnetCard.vue korzysta z centralnie zarządzanych reguł walidacyjnych z rules-utils.ts, co poprawia czytelność, modularność i łatwość utrzymania kodu.
Show full message · 481 lines Copy first response
Not yet included in a published release.
<template>
<titled-card :title="title" toolbar close-button @close="discard">
<loading-container
:is-loaded="isLoaded"
fluid
class="ma-1 pa-0 pr-3"
style="min-width: min(700px, 95vw)">
<v2-form :validator="formRef">
<v-row dense>
<v-col cols="8" sm="6">
<v2-text-field
v-model="model.name"
:rules="nameRules"
:readonly="readonly"
class="mb-2"
label="Nazwa" />
</v-col>
<v-col cols="8" sm="6">
<v2-text-field
v-model="model.printerId"
:rules="nameRules"
:readonly="readonly"
class="mb-2"
label="Id drukarki" />
</v-col>
</v-row>
<v-row dense>
<v-col cols="12" sm="6">
<v2-text-field
v-model="model.ipAddress"
:rules="ipAddressRules"
:readonly="readonly"
class="mb-2"
label="Adres IP" />
</v-col>
<v-col cols="12" sm="6">
<printer-posnet-target-selector v-model="model.targetId" />
</v-col>
</v-row>
<v-row dense>
<v-col cols="12" sm="6" class="d-flex align-center">
<v-switch
v-model="model.isActive"
:disabled="readonly"
label="Aktywny"
class="ma-0" />
</v-col>
<v-col cols="12" sm="6">
<organization-unit-selector
v-model="model.organizationUnitId"
:rules="organizationUnitIdRules"
:readonly="readonly"
label="Jednostka Organizacyjna"
required />
</v-col>
</v-row>
<v-row justify="end">
<v-col cols="auto">
<submit-discard-async-buttons :submit="submit" @discard="discard" />
</v-col>
</v-row>
</v2-form>
</loading-container>
</titled-card>
</template>
<script lang="ts">
import { computed, defineComponent, onMounted, ref } from "@vue/composition-api";
import LoadingContainer from "@/components/loading/loading-container.vue";
import SubmitDiscardAsyncButtons from "@/components/action-buttons/submit-discard-async-buttons.vue";
import axios from "@/lib/axios";
import TitledCard from "@/components/simple/titled-card.vue";
import { RulesUtils } from "@/lib/rules-utils";
import V2Form from "@/compatibility-layer/components/v2-form.vue";
import V2TextField from "@/compatibility-layer/components/v2-text-field.vue";
import V2Autocomplete from "@/compatibility-layer/components/v2-autocomplete.vue";
import V2Select from "@/compatibility-layer/components/v2-select.vue";
import V2FormValidator from "@/compatibility-layer/components/v2-form-validator";
import PrinterPosnet from "@/views/commerce/printers-posnet/printer-posnet";
import PrinterPosnetTargetSelector from "@/views/commerce/printers-posnet/printer-posnet-target-selector.vue";
import OrganizationUnitSelector from "@/views/commerce/common/selectors/organization-unit-selector.vue";
const PrinterPosnetCard = defineComponent({
components: {
TitledCard,
SubmitDiscardAsyncButtons,
V2Autocomplete,
V2TextField,
V2Form,
V2Select,
LoadingContainer,
PrinterPosnetTargetSelector,
OrganizationUnitSelector
},
props: {
value: {
type: String,
required: false,
default: null
},
readonly: {
type: Boolean,
required: false,
default: false
}
},
emits: ["close"],
setup(props, context) {
const isLoaded = ref(false);
const model = ref(
props.value ? PrinterPosnet.fromDto({}) : PrinterPosnet.empty()
);
const formRef = ref(V2FormValidator.create());
const organizationUnitIdRules = [
v => (!!v && Number(v) > 0) || "Niepoprawne ID jednostki organizacyjnej"
];
onMounted(async () => {
await loadData();
});
const loadData = async () => {
if (props.value) {
const response = await axios.get(`/api/services/app/PrinterPosnet/${props.value}`);
model.value = PrinterPosnet.fromDto(response.data.result);
}
isLoaded.value = true;
};
const isNew = computed(() => !props.value);
const submit = async () => {
if (!formRef.value.validate()) return;
const payload = { dto: model.value.dto };
if (isNew.value) {
await axios.post("/api/services/app/PrinterPosnet/", payload.dto);
} else {
await axios.put(`/api/services/app/PrinterPosnet/${props.value}`, payload.dto);
}
context.emit("close", true);
};
const title = computed(() => {
const prefix = "Zarządzanie Drukarkami Posnet";
const suffix = isNew.value ? "Nowa drukarka" : `Edycja drukarki: ${model.value.name}`;
return `${prefix} - ${suffix}`;
});
// Użycie reguł z RulesUtils
const nameRules = RulesUtils.MandatoryString(128);
const ipAddressRules = RulesUtils.IPAddress; // Zamiast definicji inline
return {
isLoaded,
model,
formRef,
submit,
discard: () => context.emit("close", false),
nameRules,
ipAddressRules,
organizationUnitIdRules,
title,
isNew
};
}
});
export default PrinterPosnetCard;
</script>
import ValidatePolish from "@/lib/validate-polish";
import Util from "@/lib/util";
export class RulesUtils {
public static NotEmpty = [v => !!v || "Pole wymagane"];
public static NotEmptyAllowZero = [v => v === 0 || !!v || "Pole wymagane"];
public static NotEmptyArray = [v => (!!v && v.length > 0) || "Pole wymagane"];
public static OptionalPrice = [
v =>
v === null ||
(ValidatePolish.amount(v) && Number(v) >= 0 && Number(v) < 100000) ||
"Niepoprawna wartość"
];
public static Price = [
v => (v !== "" && v !== null) || "Pole jest wymagane",
...RulesUtils.OptionalPrice
];
public static OptionalEmail = [
v => !v || (!!v && ValidatePolish.email(v)) || "Niepoprawny adres e-mail"
];
public static MandatoryEmail = [
v => (!!v && ValidatePolish.email(v)) || "Niepoprawny adres e-mail"
];
public static OptionalPhoneNumber = [
v => !v || (!!v && ValidatePolish.phoneNumber(v)) || "Niepoprawny numer telefonu"
];
public static MandatoryPesel = [
...RulesUtils.NotEmpty,
v => !v || (!!v && ValidatePolish.pesel(v)) || "Niepoprawny numer Pesel"
];
public static OptionalPesel = [
v => !v || (!!v && ValidatePolish.pesel(v)) || "Niepoprawny numer Pesel"
];
public static OptionalRegon = [
v =>
!v ||
(!!v &&
(v.length === 7 || v.length === 9 || v.length === 14) &&
Number.isInteger(Number(v))) ||
"Niepoprawny Regon"
];
public static RequiredRegon = [v => !!v || "Pole wymagane", ...RulesUtils.OptionalRegon];
public static NonNullNumber() {
return [v => !!v || v === 0 || "Wartość nie może byś pusta"];
}
public static IntegerNumber() {
return [v => (!v && v !== 0) || Number.isInteger(Number(v)) || "Wartość musi być całkowita"];
}
public static MinNumber(min: number) {
return [
v => (!v && v !== 0) || Number(v) >= min || `Wartość musi być więsza bądź równa ${min}`
];
}
public static MaxNumber(max: number) {
return [
v => (!v && v !== 0) || Number(v) <= max || `Wartość musi być mniejsza bądź równa ${max}`
];
}
public static OptionalInteger(min: number, max: number) {
return [
...RulesUtils.IntegerNumber(),
...RulesUtils.MinNumber(min),
...RulesUtils.MaxNumber(max)
];
}
public static MandatoryInteger(min: number, max: number) {
return [...RulesUtils.NonNullNumber(), ...RulesUtils.OptionalInteger(min, max)];
}
public static MandatoryString(maxChars: number, minChars?: number) {
const minCharsRules = minChars
? [v => !v || v.length >= minChars || `Pole musi mieć przynajmniej ${minChars} znaki`]
: [];
return [
v => !!v || "Pole wymagane",
v => (!!v && v.length >= 0) || "Pusta wartość",
v => (!!v && v.length >= 0 && v.length < maxChars) || "Nazwa za długa",
...minCharsRules
];
}
public static OptionalString(maxChars: number, minChars?: number) {
const minCharsRules = minChars
? [v => !v || v.length >= minChars || `Pole musi mieć przynajmniej ${minChars} znaki`]
: [];
return [
v => !v || (!!v && v.length >= 0 && v.length < maxChars) || "Nazwa za długa",
...minCharsRules
];
}
public static PostalCode() {
return [v => (!!v && /^[0-9]{2}-[0-9]{3}$/.test(v)) || "Niepoprawny kod pocztowy"];
}
public static ExcludedHtmlControlSequences() {
return RulesUtils.ExcludedStrings(["<!--", "-->"]);
}
public static ExcludedStrings(vals: string[]) {
return vals.map(
exV => v => !`${v}`.includes(exV) || `Tekst zawiera niedozwolone sekwencje znaków: ${exV}`
);
}
public static isValidPercent(v: any) {
return Number.isInteger(Number(v * 100)) && Number(v) >= 0 && Number(v) <= 100;
}
public static isValidAmount(v: any, max: number) {
return ValidatePolish.amount(v) && Number(v) >= 0 && Number(v) < max;
}
public static OptionalPercentRules = [
v => (!v && v !== 0) || RulesUtils.isValidPercent(v) || "Niepoprawna wartość"
];
public static OptionalAmountRules(max?: number) {
return [
v => (!v && v !== 0) || RulesUtils.isValidAmount(v, max || 100000) || "Niepoprawna wartość"
];
}
public static MandatoryPercentRules = [
v => v !== "" || "Pole jest wymagane",
v => RulesUtils.isValidPercent(v) || "Niepoprawna wartość"
];
public static MandatoryAmountRules(max?: number) {
return [
v => v !== "" || "Pole jest wymagane",
v => RulesUtils.isValidAmount(v, max || 100000) || "Niepoprawna wartość"
];
}
public static MandatoryFile(maxSize: number) {
return [
v => {
if (!v) return "Pole obowiązkowe";
if (v.size > maxSize) {
return `Załączony plik musi mieć rozmiar mniejszy od ${Util.formatBytes(
maxSize
)}`;
}
return true;
}
];
}
public static optionalBankAccount = [
v => !v || (!!v && RulesUtils.isBankAccountValid(v)) || "Podaj prawidłowy numer konta bankowego"
];
public static mandatoryBankAccount = [
...RulesUtils.NotEmpty,
...RulesUtils.optionalBankAccount
];
// Nowa reguła walidacji adresu IP
public static IPAddress = [
v =>
/^(25[0-5]|2[0-4]\d|[01]?\d\d?)\.(25[0-5]|2[0-4]\d|[01]?\d\d?)\.(25[0-5]|2[0-4]\d|[01]?\d\d?)\.(25[0-5]|2[0-4]\d|[01]?\d\d?)$/.test(v) ||
"Niepoprawny adres IP"
];
public static OptionalIPAddress = [
v => !v || /^(25[0-5]|2[0-4]\d|[01]?\d\d?)\.(25[0-5]|2[0-4]\d|[01]?\d\d?)\.(25[0-5]|2[0-4]\d|[01]?\d\d?)\.(25[0-5]|2[0-4]\d|[01]?\d\d?)$/.test(v) ||
"Niepoprawny adres IP"
];
// ... istniejące metody ...
public static optionalBankAccount = [
v => !v || (!!v && RulesUtils.isBankAccountValid(v)) || "Podaj prawidłowy numer konta bankowego"
];
public static mandatoryBankAccount = [
...RulesUtils.NotEmpty,
...RulesUtils.optionalBankAccount
];
private static isBankAccountValid(nrb: string) {
nrb = nrb.replace(/[^0-9]+/g, "");
const weights = [
1, 10, 3, 30, 9, 90, 27, 76, 81, 34, 49, 5, 50, 15, 53, 45, 62, 38, 89, 17, 73, 51, 25, 56,
75, 71, 31, 19, 93, 57
];
if (nrb.length !== 26) {
return false;
}
nrb = nrb + "2521";
nrb = nrb.substring(2) + nrb.substring(0, 2);
let Z = 0;
for (let i = 0; i < 30; i++) {
Z += parseInt(nrb[29 - i]) * weights[i];
}
return Z % 97 === 1;
}
}