validateFormメソッドを使用してJavaScriptのバリデーションをカスタマイズする

このサンプルでは、validateFormメソッドを使用して、JavaScriptコードにて、 複雑な独自のフォームバリデーションおよびフィールド計算ロジックを追加する方法を紹介しています。

window.onload = function() { //DsPdfViewer.LicenseKey = "***key***"; let viewer; window.gcd = function(a, b) { if (!b) return a; return gcd(b, a % b); } window.solveForm = function() { let fldValue1 = viewer.findAnnotation('fldValue1', {findField: 'fieldName'}), fldValue2 = viewer.findAnnotation('fldValue2', {findField: 'fieldName'}), fldResult = viewer.findAnnotation('fldResult', {findField: 'fieldName'}); Promise.all([fldValue1, fldValue2, fldResult]).then(function(arr) { fldValue1 = arr[0][0].annotation; fldValue2 = arr[1][0].annotation; fldResult = arr[2][0].annotation; fldResult.fieldValue = gcd(fldValue1.fieldValue, fldValue2.fieldValue); viewer.updateAnnotation(0, fldResult); }); } window.validateForm = function() { let a, b, result, expectedAnswer; let validationResult = viewer.validateForm(function(fieldValue, field) { switch(field.fieldName) { case 'fldValue1': a = parseFloat(fieldValue); break; case 'fldValue2': b = parseFloat(fieldValue); break; case 'fldResult': result = parseFloat(fieldValue); break; } if(a && b && result) { expectedAnswer = gcd(a, b); if(parseFloat(fieldValue) !== expectedAnswer) { return '不正解です'; } } return true; }, true); if(expectedAnswer) { if(validationResult !== true) { viewer.showMessage(validationResult, '正解は ' + expectedAnswer, 'error'); } else { viewer.showMessage('正解です', null, 'info'); } } else { viewer.showMessage('答えを入力してください', null, 'warn'); } setTimeout(function(){ viewer.repaint([0]); }, 100); } viewer = new DsPdfViewer("#viewer", {restoreViewStateOnLoad: false}); viewer.addDefaultPanels(); viewer.options.jsExecutionConfig = { // JSアクションを実行する前の処理(一時的な待機) before: function() { // Returned promise will be awaited before further JS execution. return new Promise(function(resolve) { if(document.activeElement && document.activeElement.blur) document.activeElement.blur(); setTimeout(resolve, 100); }); }, // JSアクション完了後の処理(今回はなし) after: function() { } }; viewer.open("/diodocs/pdfviewer/demos/product-bundles/assets/pdf/viewer-custom-validation.pdf"); }
<!DOCTYPE html> <html lang="ja"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>バリデーションのカスタマイズ</title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="./src/styles.css"> <script src="/diodocs/pdfviewer/demos/product-bundles/build/dspdfviewer.js"></script> <script src="/diodocs/pdfviewer/demos/product-bundles/build/wasmSupportApi.js"></script> <script src="/diodocs/pdfviewer/demos/resource/js/init.js"></script> <script src="./src/app.js"></script> </head> <body> <div id="viewer"></div> </body> </html>
#viewer { height: 100%; }