← All articlesWeb security

How to replace eval in a web calculator and validate inputs before calculation

Start reworking a web calculator by describing its behavior precisely: which numbers it accepts, which operations it performs, and what it displays when an error occurs. Then replace eval with explicit arithmetic and check the entire path from input to result. We will use a completely fictional calculator and our own synthetic data, without covering a formula language, HTML sanitization, or a CSP rollout through Report-Only.

Define the calculator contract first

In our fictional product, the user supplies two required integers from −100 to 100 inclusive and an operation name. Only add, subtract, and multiply are allowed. These are rules chosen for this example, not universal OWASP requirements: other products need their own ranges and sets of operations.

For text fields, define the format as decimal digits optionally preceded by a single minus sign. Spaces, a plus sign, a fractional part, and exponential notation are rejected. Leading zeros are allowed. An empty or missing field is an error. This contract lets developers implement unambiguous checks and product owners approve specific interface behavior.

Validate inputs before arithmetic

The trust boundary lies between the received values and the application's calculation logic. Both operands and the operation must be validated before crossing that boundary. Syntactic validation checks whether the input matches the accepted format. Semantic validation determines whether the number is within range and the requested operation is allowed.

In this implementation, field presence and the format of text values are checked first. The values are then converted to numbers and checked against the range. The operation name must exactly match one of the three allowed values. This rule also applies to values from a dropdown: having an option in the interface does not replace validation of the received data. If any check fails, processing stops with a clear error.

Replace eval with explicit operation selection

Once all fields pass validation, the calculation logic selects an operation through explicit branching: add adds the two operands, subtract subtracts the second from the first, and multiply multiplies them. This approach requires no expression string to be assembled and passed to eval. An unsupported operation must be rejected rather than evaluated through another mechanism.

Trace the path from reading the fields to displaying the result. As part of the implementation review proposed here, confirm that validation precedes arithmetic, eval has been removed from this path, and user-supplied text is not passed to another JavaScript execution mechanism. A few correct numerical answers alone do not confirm that eval has been removed: that requires implementation analysis.

Test correct answers and observable rejections

The following checks are acceptance tests proposed for this fictional calculator, not an official procedure from the documentation. Run them using your own synthetic data. As positive controls, add(2, 3) should display 5, subtract(2, 3) should display −1, and multiply(2, 3) should display 6. For boundary checks, try add(−100, 0) and add(100, 0), for example: the expected results are −100 and 100, respectively.

Then submit −101, 101, an empty string, 1.5, 1e2, a value containing a space, and a request missing one operand, one case at a time. Separately, request divide with valid numbers. Every case should produce a clear error without a numerical result. Repeat the rejection cases after a successful calculation: the previous number must not appear to answer the new input. If an HTTP request is involved, a successful status alone is insufficient—check the response content and the interface state.

Apply the same contract on the server if it performs calculations

If the calculator sends data to a server-side handler, browser checks do not replace server-side validation. The server must independently validate both values and confirm that the operation exactly matches the allowed set before calculating. Processing must not continue for a partially validated request.

For a hypothetical test proposed here, send synthetic invalid values directly to your own test handler, bypassing the form. Expect rejection without a calculation or numerical result; for a valid add(2, 3), expect 5. Check these properties in the handler's response, rather than relying only on the HTTP status. If the calculator runs entirely locally, the server-side checks do not apply.

Test CSP as an additional restriction

The unsafe-eval value in CSP permits the use of eval. For a separate test proposed here in your own environment, apply an enforcing Content-Security-Policy header with script-src 'self' and without unsafe-eval, and load the calculator as a separate permitted script from the same origin. Check the policy actually received by the browser: merely omitting unsafe-eval without restricting scripts is insufficient.

The criteria for this test are that ordinary addition of 2 and 3 displays 5, while a separate test call to eval with the fixed, harmless string “2 + 3” is blocked by the browser. This test call is only intended to verify the restriction in your own environment. A Report-Only policy does not block execution. CSP remains an additional layer: this result does not replace analysis confirming the removal of eval and does not prove the absence of other vulnerabilities.

Prioritize the fixes

First, agree on the contract, implement validation before calculation, and replace eval with explicit operations. Then confirm correct answers, clear rejections, and clearing of the previous result; if a server is involved, repeat the checks against its handler. Test the additional CSP restriction separately. Passing these examples confirms only the observed behavior under the chosen conditions, not guaranteed product security.

This approach is intended for a simple calculator with fixed operations; creating a formula language is outside its scope. If you need an assessment of your website or the web component of your product, you can start with a free CheckMyApp audit and discuss checking input handling in specific calculation scenarios.

Sources and documentation

  1. Input Validation Cheat Sheet
  2. Content Security Policy Cheat Sheet
CheckMyApp

Check your application’s security.

Enter your web application address and email. Get a free preliminary report and choose the depth of analysis.

Check for free