메인 콘텐츠로 건너뛰기

field 존재 여부 확인

예를 들어, MyField field가 존재하며 값이 채워졌는지 확인해 보겠습니다.
var field = Context.GetField("MyField");

if (!field) {
  Context.CheckSucceeded = false;
  Context.ErrorMessage = 'MyField field를 찾을 수 없습니다';
} else if (!field.Value) {
  Context.CheckSucceeded = false;
  Context.ErrorMessage = 'MyField field가 비어 있습니다';
}

부동소수점 수 비교

부동소수점 수를 직접 비교하면 예측할 수 없는 결과가 발생할 수 있습니다. 숫자 값, 특히 금액 값을 정확하게 비교하려면 Math 내장 객체의 메서드를 사용할 것을 권장합니다.
// 두 부동 소수점 숫자 비교
var floatField1 = Context.GetField("Number Field 1");
var floatField2 = Context.GetField("Number Field 2");
var floatVal1 = floatField1.Value;
var floatVal2 = floatField2.Value;

if (Math.round(floatVal1) === Math.round(floatVal2)) {
    return;
} else {
    Context.CheckSucceeded = false;
    Context.ErrorMessage = '값이 다릅니다';
}

// 두 금액 값 비교
var moneyField1 = Context.GetField("Money Field 1");
var moneyField2 = Context.GetField("Money Field 2");
var value1 = moneyField1.Value.Amount;
var value2 = moneyField2.Value.Amount;

if (Math.abs(value1 - value2) <= 0.0001) {
    return;
} else {
    Context.CheckSucceeded = false;
    Context.ErrorMessage = '값이 다릅니다';
}

다른 field에 따라 값이 비어 있지 않도록 요구하기

선택적 field라도, 다른 field의 값에 따라 필수 항목이 될 수 있습니다. 예를 들어 혼인 상태가 “married”로 인식되면 배우자의 이름을 반드시 입력해야 합니다. 또는 생년월일로 계산한 나이가 미성년자임을 보여 주면 보호자의 서명이 필요합니다. 이 script rule은 혼인 상태 field의 값이 “Married”인 문서에서 배우자의 이름과 성이 모두 입력되어 있는지 확인합니다:
function checkFieldValuePresence(field) {
    if (!field.Value) {
        Context.ErrorMessage = 'Value of ' + field.Name + ' field should not be empty';
        return false;
    }
    return true;
}

var conditionField = Context.GetField("MaritalStatus");

if (conditionField === null) {
    Context.CheckSucceeded = false;
    Context.ErrorMessage = 'MaritalStatus field not found';
} else if (checkFieldValuePresence(conditionField)) {
    var lastName = Context.GetField("SpouseLastName");
    var firstName = Context.GetField("SpouseFirstName");
    if (conditionField.Text === "Married") {
        if (lastName === null || firstName === null) {
            Context.CheckSucceeded = false;
            Context.ErrorMessage = 'Spouse name field not found';
        } else if (!checkFieldValuePresence(lastName) || !checkFieldValuePresence(firstName)) {
            Context.CheckSucceeded = false;
        }
    }
} else { // 결혼 여부 미입력, 검사 실패
    Context.CheckSucceeded = false;
}

field가 문서에서 찾아졌는지 확인

규칙을 사용하면 값이 실제로 문서에 인쇄되어 있지 않더라도 field 값을 채울 수 있습니다. 예를 들어, 여러 세금이 적용되는 경우 총 세액을 자동으로 계산할 수 있습니다. 그러나 일부 국가에서는 세액 합계를 문서에 인쇄해야 합니다. 이 스크립트 규칙은 독일에서 발급된 영수증의 경우 세액 합계가 단순히 계산만 되는 것이 아니라 이미지 상에 실제로 존재하는지 확인합니다. 다른 국가의 경우에는 세액 합계 field에 대해 Required field 플래그가 켜져 있기 때문에 별도의 추가 검사가 필요하지 않습니다:
function checkFieldRegion(field) {
    if (!field || !field.HasRegion) {
        Context.ErrorMessage = '(' + field.Name + ') field가 문서 이미지에 없습니다';
        return false;
    }
    return true;
}

var conditionField = Context.GetField("CountryOfOrigin");

if (!conditionField.Value) {
    Context.ErrorMessage = 'Country of origin unknown, cannot check taxes';
    Context.CheckSucceeded = false;
} else {
    var totalTaxField = Context.GetField("TotalTax");
    if (conditionField.Text === "DE" && !checkFieldRegion(totalTaxField)) {
        Context.CheckSucceeded = false;
    }
}

특정 경우의 데이터 검증

총 세금이 모든 세금 항목의 합과 같은지 확인하는 작업은 미리 정의된 규칙(Check Sum)을 사용하여 수행할 수 있습니다. 그러나 일부 국가에서는 세금 항목 중 하나가 음수 값을 가질 수 있으므로, 이 두 경우를 모두 처리할 수 있는 것은 스크립트 규칙뿐입니다. 문서의 발행 국가에 따라 모든 세금을 단순히 합산하거나, 세금 환급이 있는 경우 해당 세금을 음수로 처리해 합산·차감하도록 할 수 있습니다. 다음 예제 스크립트는 두 세금 항목의 합이 총 세금과 같은지 확인하되, 영수증이 스페인에서 발행된 경우에는 두 세금의 합 또는 차이 중 어느 한 쪽이 총 세금과 같도록 허용합니다:
var conditionField = Context.GetField("CountryOfOrigin");
var totalTaxField = Context.GetField("TotalTax");
var tax1Field = Context.GetField("Tax1");
var tax2Field = Context.GetField("Tax2");

if (!conditionField.Value || !totalTaxField.Value || !tax1Field.Value || !tax2Field.Value) {
    Context.ErrorMessage = '세금을 확인할 수 없음';
    Context.CheckSucceeded = false;
} else {
    if (conditionField.Text === "ES") {
        Context.CheckSucceeded = ((Math.round(tax1Field.Value - tax2Field.Value) === Math.round(totalTaxField.Value))
            || (Math.round(tax1Field.Value + tax2Field.Value) === Math.round(totalTaxField.Value)));
    } else {
        Context.CheckSucceeded = (Math.round(tax1Field.Value + tax2Field.Value) === Math.round(totalTaxField.Value));
    }
}

표 열 합계를 표 외부에 있는 값과 비교하기

스크립트는 일반 field뿐만 아니라 표 내부의 값도 참조할 수 있습니다. 규칙 검사를 더 빠르게 수행하려면 표를 변수에 저장한 다음 원본 표 대신 해당 변수를 참조할 것을 권장합니다. 변수에 전체 표가 포함되어 있으면 Instances 속성을 사용하여 표의 행에 액세스한 다음, Field GetChild 메서드를 사용하여 특정 행의 특정 셀 값을 가져올 수 있습니다. 아래 샘플 스크립트는 Total Price 열의 모든 값을 합산한 뒤 그 결과를 Total field의 값과 비교합니다.
var totalField = Context.GetField("Total");
var tableField = Context.GetField("MyTable");

if (!totalField) {
    Context.CheckSucceeded = false;
    Context.ErrorMessage = "합계 field를 찾을 수 없습니다";
    return;
}

if (!tableField) {
    Context.CheckSucceeded = false;
    Context.ErrorMessage = "MyTable field를 찾을 수 없습니다";
    return;
}

var sum = 0;

for (var i = 0; i < tableField.Instances.length; i++) {
    var tableTotalField = tableField.Instances[i].GetChild("MyTable/Total Price");
    sum += tableTotalField.Value.Amount;
}

if (Math.abs(sum - totalField.Value.Amount) > 0.02) {
    Context.CheckSucceeded = false;
    Context.ErrorMessage = "테이블의 Total Price 합계가 합계와 일치하지 않습니다";
}

테이블 열의 개별 셀 값을 테이블 외부의 값과 비교하고, 오류가 있는 행 번호 표시하기

테이블 열 참조는 Field GetFields 메서드를 사용해서도 수행할 수 있습니다. 이 메서드를 사용하면 테이블의 모든 셀 목록을 가져올 수 있으며, 루프를 설정할 때 유용합니다. 아래 예제 스크립트는 각 품목 라인의 세율을 전체 세율과 비교합니다. 값이 일치하지 않더라도 스크립트는 중단되지 않습니다. 대신, 불일치가 발생한 행 번호가 특수 변수에 전달되며, 규칙은 이 변수를 사용해 전체 열을 검사할 수 있습니다. 예제 스크립트의 오류 메시지에는 오류가 있는 모든 행 번호가 나열됩니다:
var taxRateFields = Context.GetFields("MyTable/TaxRate");
var taxRateField = Context.GetField("TaxRate");

if (!taxRateFields || !taxRateField)
    return;

var taxRate = taxRateField.Value ? taxRateField.Value : 0;
var wrongLines = [];
for (var i = 0; i < taxRateFields.length; i++) {
    if (taxRateFields[i].Value != taxRate)
        wrongLines.push(i + 1);
}

if (wrongLines.length > 0) {
    Context.CheckSucceeded = false;
    Context.ErrorMessage = "다음 행의 세율이 올바르지 않습니다: " + wrongLines.join(", ");
}

한 행에서 여러 field의 곱을 동일 행의 다른 field 값과 비교하기

표의 서로 다른 열에 대해 반복문을 사용하지 않고도 순차적으로(행 단위로) 다양한 연산을 수행할 수 있습니다. 이를 위해서는 각 열을 Field GetField 메서드를 사용하여 참조해야 합니다. 이렇게 정의한 규칙은 표의 각 행에 대해 자동으로 반복 실행됩니다. 이 방식으로 참조되는 모든 열은 동일한 표에 속해야 합니다. 아래 예제 스크립트는 각 행에서 수량에 단가를 곱한 뒤, 그 결과 값을 해당 품목의 총 금액과 비교합니다:
var quantityField = Context.GetField("MyTable/Quantity");
var unitPriceField = Context.GetField("MyTable/Unit Price");
var totalField = Context.GetField("MyTable/Total Price");

if (!quantityField || !unitPriceField || !totalField)
    return;

var quantity = quantityField.Value ? quantityField.Value : 0;
var unitPrice = unitPriceField.Value?.Amount ? unitPriceField.Value.Amount : 0;
var total = totalField.Value?.Amount ? totalField.Value.Amount : 0;

var result = quantity * unitPrice;

if (Math.abs(result - total) > 0.01) {
    Context.CheckSucceeded = false;
    Context.ErrorMessage = "수량 * 단가가 합계와 같지 않습니다";
}