Server-Side Form Validation Using an Event


                        
        
            Survey.StylesManager.applyTheme("defaultV2");
        

function validateCountry(_, { data, errors, complete }) {
  const countryName = data["country"];
  if (!countryName) {
    complete();
    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;
      if (!found) {
        errors["country"] = "Country is not found";
      }
      complete();
    });
}

                
                    var json = {
  "elements": [
    {
      "type": "text",
      "name": "country",
      "title": "Enter a country",
      "isRequired": true
    }
  ],
  "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);
            });
        
survey.onServerValidateQuestions.add(validateCountry);        
            $("#surveyElement").Survey({
            model: survey 
            });
        

                    
<!DOCTYPE html>
<html lang="en">
<head>
    <title>Server-Side Form Validation Using an Event, jQuery Example | SurveyJS</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 handle an event to process user input on the server side. SurveyJS also allows you to build an validation expression for the same purpose. 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.

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. Refer to the following demo for more information: Server-Side Form Validation Using Expressions.

Handle the onServerValidateQuestions Event

An onServerValidateQuestions event handler accepts the survey as the first argument and an object with the following fields as the second argument:

  • data - An object that contains question values.
  • errors - An object for your error messages. Set error messages as follows: errors["questionName"] = "My error message";
  • complete() - A method that you should call when the request to the server has completed.

In this server-side validation example, you should enter a country name into the form field. A callback assigned to the onServerValidateQuestions event handler 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.

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.