Server-Side Form Validation Using Expressions


                        
        
            Survey.StylesManager.applyTheme("defaultV2");
        

function doesCountryExist([ countryName ]) {
  if (!countryName) {
    this.returnResult();
    return;
  }
  fetch("https://surveyjs.io/api/CountriesExample?name=" + countryName)
    .then((response) => {
      if (!response.ok) {
        throw new Error(`HTTP error! Status: ${response.status}`);
      }
      return response.json();
    })
    .then((data) => {
      const found = data.length > 0;
      this.returnResult(found);
    });
}

Survey.FunctionFactory.Instance.register("doesCountryExist", doesCountryExist, true);

                
                    var json = {
  "checkErrorsMode": "onValueChanged",
  "elements": [{
    "type": "text",
    "name": "country",
    "title": "Enter a country",
    "isRequired": true,
    "validators": [{
      "type": "expression",
      "text": "Country is not found",
      "expression": "doesCountryExist({country})"
    }]
  }],
  "showQuestionNumbers": false
};

                    window.survey = new Survey.Model(json);
                
        
            survey.onComplete.add(function(sender) {
            document.querySelector('#surveyResult').textContent =
            "Result JSON:\n" + JSON.stringify(sender.data, null, 3);
            });
        
        
            $("#surveyElement").Survey({
            model: survey 
            });
        

                    
<!DOCTYPE html>
<html lang="en">
<head>
    <title>Async Form Validation Using Expressions | jQuery Example</title>
    
<meta name="viewport" content="width=device-width" />
    <script src="https://unpkg.com/jquery"></script>
    <script src="/DevBuilds/survey-jquery/survey.jquery.min.js"></script>
    <link href="/DevBuilds/survey-core/defaultV2.min.css" type="text/css" rel="stylesheet" />
    <link rel="stylesheet" href="./index.css">

</head>
<body style="margin: 0">
    
            <div id="surveyElement" style="display:inline-block;width:100%;">
                            </div>
    <div id="surveyResult"></div>

<script type="text/javascript" src="./index.js"></script>

</body>
</html>
Loading...
Sorry, we can't retrieve the data from server. Please comeback later.

This example demonstrates how you can build a validation expression that processes user input on the server side. You need to register a custom function that can be used in expressions. Such a function can query the server. SurveyJS also allows you to validate input in an event handler. This article explains the difference between server-side input validation using expressions and an event handler. Select React, Vue, Knockout, jQuery, or Angular to view an example for your JavaScript framework of choice.

Event Handler vs Expressions

Event Handler

You can validate user input in the onServerValidateQuestions event handler. Survey authors have no access to this handler and therefore cannot disable custom validation. The event handler is executed on navigation to the next page and on survey completion. This behavior does not allow for immediate validation. Refer to the following demo for more information: Server-Side Form Validation Using an Event.

Expressions

If you want to query the server from an expression, implement and register a custom validator in your JavaScript code. Survey authors cannot modify the validator, but they can decide whether or not to use it in their expressions when they design their surveys. Immediate validation is available.

Implement a Custom Async Validator

Follow the steps below to implement a custom asynchronous validator:

  1. Create a JavaScript function that validates data.
    This function should perform an asynchronous operation, for example, send a request to a server. Once the operation is complete, call the this.resultData method with a Boolean value that indicates a validation result.

  2. Register the function in FunctionFactory.
    The following code registers the myFunc function under the name foo. The third parameter specifies that this function is asynchronous:

    import { FunctionFactory } from "survey-core";
    FunctionFactory.Instance.register("foo", myFunc, true);
    
  3. Use the validator within expressions.
    To reference the validator within an expression, use curly brackets: {foo}.

In this server-side validation example, you should enter a country name into the form field. The custom validator (doesCountryExist) will fetch a list of countries and check whether the entered country is in it. If the country is not found, the form field will display a validation error. Validation is triggered immediately after you answer the question because the Survey's checkErrorsMode property is set to "onValueChanged". If you do not set this property, validation activates before a user proceeds to the next page or completes the survey.

Why we use cookies.

This site uses cookies to make your browsing experience more convenient and personal. Cookies store useful information on your computer to help us improve the efficiency and relevance of our site for you. In some cases, they are essential to making the site work properly. By accessing this site, you consent to the use of cookies.

For more information, refer to DevSoft Baltic’ privacy policy and cookie policy.