Data Validation
Data validation ensures that respondents fill out all required form fields and the format of values is correct before they are submitted to the server. SurveyJS Form Library supports data validation on the client and server side and allows you to validate user responses immediately after an answer is entered or when respondents proceed to the next page or end the survey. Refer to the following sections for information on how to add and configure data validation in your survey:
- Enable Immediate Data Validation
- Built-In Client-Side Validators
- Implement Custom Client-Side Validation
- Server-Side Validation
- Postpone Validation Until Survey Ends
- Switch Between Pages with Validation Errors
Enable Immediate Data Validation
By default, data validation activates when a respondent proceeds to the next page. 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 respondent leaves an input field, set the Survey's checkErrorsMode
property to "onValueChanged"
. In addition, you can set the textUpdateMode
property to "onTyping"
if you want to validate text input while users are typing.
const surveyJson = {
"checkErrorsMode": "onValueChanged",
"textUpdateMode": "onTyping",
"elements": [
// ...
]
}
Alternatively, you can postpone data validation until a respondent completes the 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 been 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})"
}]
}]
};
Postpone Validation Until Survey Ends
Your survey can trigger data validation when a respondent clicks the Complete button. If the survey contains validation errors, it will take the respondent to the page with the first error and focus the question with the invalid answer. To activate this behavior, set the checkErrorsMode
property to "onComplete"
:
const surveyJson = {
"checkErrorsMode": "onComplete",
"elements": [
// ...
]
}
Switch Between Pages with Validation Errors
By default, a respondent cannot leave a page that contains validation errors. If you want to let a respondent switch between pages regardless of whether they have validation errors or not, enable the validationAllowSwitchPages
property as follows:
import { Model, NumericValidator } from "survey-core";
const surveyJson = { ... }
const survey = new Model(surveyJson);
survey.validationAllowSwitchPages = true;