Data Validation
SurveyJS Form Library allows you to validate user responses on the client or server side. Regardless of the type, validation activates before a user proceeds to the next page or completes the survey. If the current page contains errors, the survey indicates them and focuses the first question with an invalid answer. If you want to run validation immediately after a user answers a question, set the Survey's checkErrorsMode
property to "onValueChanged"
:
const surveyJson = {
"checkErrorsMode": "onValueChanged",
"elements": [
// ...
]
}
Refer to the sections below for information on how to enable validation in your survey:
Built-In Client-Side Validators
SurveyJS Form Library supports multiple built-in client-side validators. The Required validator ensures that a question value is not empty. Enable a question's isRequired
property to add the Required validator to this question. In addition, you can specify the requiredErrorText
property to override the default error message:
const surveyJson = {
"elements": [{
"name": "question1",
"type": "text",
"isRequired": true,
"requiredErrorText": "Value cannot be empty"
}]
}
If you want to specify the required state dynamically based on a condition, use the requiredIf
property. Refer to the following help topic for more information: Conditional Visibility.
Other validators are implemented as JavaScript classes. You can create an object of a validator class and push it to a question's validators
array. Set the text
property in the class constructor if you want to override the default error message:
import { Model, NumericValidator } from "survey-core";
const surveyJson = { ... }
const survey = new Model(surveyJson);
const question = survey.getQuestionByName("question1")
question.validators.push(new NumericValidator({ text: "Value must be a number" }));
Alternatively, you can declare the validators
array in the survey JSON schema:
const surveyJson = {
"elements": [{
"name": "question1",
"type": "text",
"validators": [
{ "type": "numeric", "text": "Value must be a number" }
]
}]
}
The following class-based validators are available:
type (for JSON) |
Validator Class (for JavaScript) | Description |
---|---|---|
"numeric" |
NumericValidator |
Throws an error if the answer is not a number or if an entered number is outside the minValue and maxValue range. Alternatively, you can set the min and max properties in the question object to specify the range. |
"text" |
TextValidator |
Throws an error if the length of entered text is outside the range between minLength and maxLength . |
"email" |
EmailValidator |
Throws an error if an entered value is not a valid e-mail address. |
"expression" |
ExpressionValidator |
Throws an error when the expression evaluates to false (see Expressions). |
"answercount" |
AnswerCountValidator |
Throws an error if a user selects fewer choices than specified by minCount or more choices than specified by maxCount . Applies only to question types that can have multiple values (for instance, Checkbox). |
"regex" |
RegexValidator |
Throws an error if an entered value does not match a regular expression defined in the regex property. |
Implement Custom Client-Side Validation
SurveyJS Form Library raises the onValidateQuestion
event, which you can handle to add custom validation logic to your survey. For example, the following code checks that the answer to a "memo"
question contains the word "survey":
import { Model } from "survey-core";
const surveyJson = {
"elements": [{
"name": "memo",
"type": "comment",
// ...
}]
};
const survey = new Model(surveyJson);
survey.onValidateQuestion.add((survey, options) => {
if (options.name === "memo") {
if (options.value.indexOf("survey") === -1) {
options.error = 'Your answer must contain the word "survey"'
}
}
});
Alternatively, you can use expressions to implement custom validation. Create a custom function, register it, and then call it from within your expression. The following code uses this technique to implement the same value validation scenario:
import { FunctionFactory } from "survey-core";
function validateComment (params) {
const value = params[0];
return value.indexOf("survey");
}
FunctionFactory.Instance.register("validateComment", validateComment);
const surveyJson = {
"elements": [{
"name": "memo",
"type": "comment",
"validators": [{
"type": "expression",
"text": "Your answer must contain the word \"survey\"",
"expression": "validateComment({memo}) >= 0"
}]
// ...
}]
};
Server-Side Validation
If your validation logic requires a request to a server, make this request within the onServerValidateQuestions
event handler. It 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 has completed.
In the following example, a callback assigned to the onServerValidateQuestions
event handler fetches a list of countries and checks if an entered country is in this list:
import { Model } from "survey-core";
const surveyJson = {
"elements": [{
"name": "country",
"type": "text",
// ...
}]
};
const survey = new Model(surveyJson);
function validateCountry(survey, { 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();
});
}
survey.onServerValidateQuestions.add(validateCountry);
Alternatively, you can use expressions to implement custom validation. Create an asynchronous function, register it, and then call it within your expression. The following code uses this technique to implement the previously demonstrated validation scenario:
import { FunctionFactory } from "survey-core";
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);
});
}
FunctionFactory.Instance.register("doesCountryExist", doesCountryExist, true);
const surveyJson = {
"elements": [{
"type": "text",
"name": "country",
"title": "Type a country:",
"validators": [{
"type": "expression",
"text": "Country is not found",
"expression": "doesCountryExist({country})"
}]
}]
};