Example of Stepper Validation in ASP.NET MVC Stepper Control
This sample showcases the integration of validation support in the Stepper component.
@Html.UiStepper(new UiStepperOptions { Id = "validation-stepper", Steps = (List<UiStep>)ViewData["StepperWithText"], Linear = true, OnStepChanging = "handleStepChange" })
<style>
@@font-face {
font-family: 'Survey-icons';
src:
url(data:application/x-font-ttf;charset=utf-8;base64,AAEAAAAKAIAAAwAgT1MvMj1tSfkAAAEoAAAAVmNtYXC1L7WCAAABkAAAAEpnbHlmDbWrlAAAAegAAAKgaGVhZCXq4xcAAADQAAAANmhoZWEIEgQFAAAArAAAACRobXR4EAAAAAAAAYAAAAAQbG9jYQHmAPwAAAHcAAAACm1heHABFgCIAAABCAAAACBuYW1l7hSegAAABIgAAAJhcG9zdHtFxzkAAAbsAAAATAABAAAEAAAAAFwEAAAAAAADtQABAAAAAAAAAAAAAAAAAAAABAABAAAAAQAAUEyd5l8PPPUACwQAAAAAAOGLzxMAAAAA4YvPEwAAAAADtQP0AAAACAACAAAAAAAAAAEAAAAEAHwACAAAAAAAAgAAAAoACgAAAP8AAAAAAAAAAQQAAZAABQAAAokCzAAAAI8CiQLMAAAB6wAyAQgAAAIABQMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUGZFZABA5wDnBwQAAAAAXAQAAAAAAAABAAAAAAAABAAAAAQAAAAEAAAABAAAAAAAAAIAAAADAAAAFAADAAEAAAAUAAQANgAAAAgACAACAADnAOcD5wf//wAA5wDnA+cH//8AAAAAAAAAAQAIAAgACAAAAAEAAgADAAAAAAAAAJYA/AFQAAAAAwAAAAADtQP0ADMANwB7AAATFR8KMxc1Mz8KNS8KIQ8KJREhESUhIw8OERUfDiEzPw4TLw7xAQMEBQYHCAgIDhCA0SkPDQsKCAYGBAQEAwEDBAUHBwcICA4Q/oUODQsKCAcFBAQDAwJw/TwCm/2PDQsLCgkICAcHCwkHBQYCAQECAgMDBAQFCgsMDBELDQKACwsKCggJBwcMCggHBQQCAwEBAQECAwMHCAoKCwsLChMCu9AODQsKCA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luY2Z1c2lvbi5jb20AIABTAHUAcgB2AGUAeQAtAGkAYwBvAG4AcwBSAGUAZwB1AGwAYQByAFMAdQByAHYAZQB5AC0AaQBjAG8AbgBzAFMAdQByAHYAZQB5AC0AaQBjAG8AbgBzAFYAZQByAHMAaQBvAG4AIAAxAC4AMABTAHUAcgB2AGUAeQAtAGkAYwBvAG4AcwBGAG8AbgB0ACAAZwBlAG4AZQByAGEAdABlAGQAIAB1AHMAaQBuAGcAIABTAHkAbgBjAGYAdQBzAGkAbwBuACAATQBlAHQAcgBvACAAUwB0AHUAZABpAG8AdwB3AHcALgBzAHkAbgBjAGYAdQBzAGkAbwBuAC4AYwBvAG0AAAAAAgAAAAAAAAAKAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAQIBAwEEAQUACGNvbW1lbnRzCmZvcm0tMDUtd2YKZm9ybS1vay13ZgAA) format('truetype');
font-weight: normal;
font-style: normal;
}
[class^="sf-icon-"],
[class*=" sf-icon-"] {
font-family: 'Survey-icons' !important;
speak: none;
font-size: 18px;
font-style: normal;
font-weight: normal;
font-variant: normal;
text-transform: none;
line-height: inherit;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
.sf-icon-survey-feedback:before {
content: "\e700";
}
.sf-icon-survey-intro:before {
content: "\e703";
}
.sf-icon-survey-status:before {
content: "\e707";
}
#validation-step-content input[type=radio] {
vertical-align: top;
}
.feedback-label {
margin-bottom: 10px;
}
#feedback-text {
color: #000;
width: 90%;
height: 50px;
resize: vertical;
}
#agreement-text p {
text-align: justify;
}
#validation-step-content .success-message {
color: green;
font-weight: bold;
margin-top: 10px;
font-size: 16px;
}
#validation-step-content .required {
color: red;
}
#validation-step-content .content-wrapper {
min-height: 200px;
}
#validation-step-content .error-label {
height: 20px;
color: #e5184b;
font-size: 12px;
font-weight: 600;
line-height: 15px;
visibility: hidden;
margin: 3px 0 0;
}
#validation-step-content .question-container {
display: flex;
flex-direction: column;
gap: 10px;
}
.validation-stepper-section {
width: 70%;
margin: 40px auto;
}
#validation-step-content {
position: relative;
width: 65%;
min-height: 250px;
margin: 0 auto;
}
.step-content {
position: absolute;
top: 0;
left: 0;
width: 100%;
opacity: 0;
pointer-events: none;
}
/* Display the active step content */
.step-content.step-active {
animation: fadeInUp 0.4s;
opacity: 1;
pointer-events: all;
}
/* Keyframes */
@@keyframes fadeInUp {
from {
opacity: 0;
-webkit-transform: translate3d(0, 50%, 0);
transform: translate3d(0, 50%, 0);
}
to {
opacity: 1;
-webkit-transform: none;
transform: none;
}
}
@@media only screen and (max-width: 965px) {
.validation-stepper-section {
width: 100%;
}
#validation-step-content {
width: auto;
margin: auto 5%;
}
}
@@media only screen and (max-width: 650px) {
#validation-step-content {
margin: auto 5% 20% 5%;
}
}
</style>
<div class="control-section">
<div class="validation-stepper-section">
@Html.UiStepper(new UiStepperOptions { Id = "validation-stepper", Steps = (List<UiStep>)ViewData["StepperWithText"], Linear = true, OnStepChanging = "handleStepChange" })
</div>
<div id="validation-step-content">
</div>
</div>
<script>
var validationStepper;
var isEmailValid = false;
var isFeedbackTextValid = false;
var isUserNavigatingReverse = false;
var isCurrentStepValid = false;
var stepperContentWrapper;
var regex = new RegExp('^[A-Za-z0-9._%+-]+@@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}$');
var stepperContents = [
"<div class='step-content step-content-0 step-active'><div id='agreement-text'><p>Welcome! This survey is an opportunity for you to share your opinions and experiences, contributing to the ongoing improvement of our offerings. Your participation is highly appreciated, and we look forward to gaining a deeper understanding of your preferences. </p></div><label style='margin-top: 15px'>Enter your email <span class='required'>*</span></label><input class='ui-input inputContainer' id='add-email' placeholder='Enter here' oninput='onInputChange(this, true)' /><div class='add-email error-label'>Email cannot be empty.</div><button style='margin-top: 20px;' class='ui-btn nextStep stepperBtn' onclick='onNextStep(this)'>Next</button></div>",
"<div class='step-content step-content-1'> <div class='question-container'> <div class='survey-question'><p> Is this the first time you have visited this website? <span class='required'>*</span></p><label> <input type='radio' class='inputContainer new-user' name='service-usage' value='yes' checked> Yes </label> <label style='margin: 0px 10px'> <input type='radio' class='inputContainer old-user' name='service-usage' value='no'> No </label></div> <div class='feedback-section'> <p class='feedback-label'>Anything else you would like to share? <span class='required'>*</span></p> <textarea id='feedback-text' class='inputContainer' placeholder='I have feedback on...' oninput='onInputChange(this)' required></textarea> <div class='feedback-area error-label' style='margin: 0'>Feedback cannot be empty.</div> </div> </div><div style='display: flex;'> <button style='margin-top: 20px; margin-right: 5%;' class='ui-btn previousStep' onclick='onPreviousStep(this)'>Previous</button> <button style='margin-top: 20px;' class='ui-btn nextStep' onclick='onNextStep(this)'>Submit Feedback</button></div></div></div>",
"<div class='step-content step-content-2'><div class='confirm-section'><div class='feedback-msg'><b>Please confirm to submit your feedback.</b></div><br/><div class='feedback-msg' id='feedback-message'></div> <button style='margin-top: 20px; margin-right: 5%;' class='ui-btn previousStep' onclick='onPreviousStep(this)'>Previous</button> <button style='margin-top: 20px; margin-right: 5%;' class='ui-btn confirmbutton' id='confirm-button' onclick='onConfirm(this)'>Confirm</button></div></div>",
"<div class='step-content step-content-3'><div class='success-section'><div class='success-message' id='success-message'>Thanks! Feedback has been submitted successfully.</div><button style='margin-top: 20px; margin-right: 5%;' type='reset' class='ui-btn e-hide' id='reset-button' onclick='onReset(this)'> Reset </button> </div></div>"
];
// The steppers's own methods (Lumen.get) stand for Syncfusion's instance: nextStep / previousStep, steps[i].isValid
window.onNextStep = function () { return validationStepper.next(); };
window.onPreviousStep = function () { return validationStepper.previous(); };
window.onConfirm = function () {
var stepContent = document.querySelector('.step-content-3');
if (!stepContent) {
stepperContentWrapper.insertAdjacentHTML('beforeend', stepperContents[3]);
stepContent = document.querySelector('.step-content.step-content-3');
}
document.querySelectorAll('.step-content').forEach(function (step) { return step.classList.remove('step-active'); });
if (stepContent) {
stepContent.classList.add('step-active');
validationStepper.setValid(validationStepper.getActiveStep(), true);
}
};
window.onInputChange = function (args, isEmailInput) {
var elementId = isEmailInput ? 'add-email' : 'feedback-area';
var errElement = document.querySelector('.' + elementId + '.error-label');
if (args.value.length === 0) {
if (isEmailInput) {
errElement.textContent = 'Email cannot be empty.';
isEmailValid = false;
} else {
errElement.textContent = 'Feedback cannot be empty.';
isFeedbackTextValid = false;
}
} else {
if (isEmailInput) {
isEmailValid = regex.test(args.value);
errElement.textContent = isEmailValid ? '' : 'Enter a valid email address.';
} else {
isFeedbackTextValid = args.value.length > 15;
errElement.textContent = isFeedbackTextValid ? '' : 'Please enter at least 15 characters.';
}
}
errElement.style.visibility = errElement.textContent ? 'visible' : 'hidden';
};
window.onReset = function () {
isCurrentStepValid = false;
validationStepper.reset();
Array.from(document.querySelectorAll('.inputContainer')).forEach(function (ele) {
ele.value = '';
if (ele.classList.contains('new-user')) { ele.checked = true; } else { ele.checked = false; }
});
for (var i = 0; i < 3; i++) { validationStepper.setValid(i, null); }
};
// Syncfusion's Created: the content of the first step
window.addEventListener('load', function () {
validationStepper = window.Lumen.get('validation-stepper');
stepperContentWrapper = document.getElementById('validation-step-content');
stepperContentWrapper.innerHTML = stepperContents[validationStepper.getActiveStep()];
});
// Syncfusion's StepChanging: a step is left only when it is right (return false = stay)
function handleStepChange(activeStep, previousStep) {
isUserNavigatingReverse = activeStep < previousStep;
if (!isUserNavigatingReverse) {
setValidState(previousStep);
} else {
validationStepper.setValid(activeStep, null);
validationStepper.setValid(previousStep, null);
isCurrentStepValid = true;
}
if (isCurrentStepValid) {
var stepContent = document.querySelector('.step-content-' + activeStep);
document.querySelectorAll('.step-content').forEach(function (step) { return step.classList.remove('step-active'); });
if (!stepContent) {
stepperContentWrapper.insertAdjacentHTML('beforeend', stepperContents[activeStep]);
stepContent = document.querySelector('.step-content.step-content-' + activeStep);
}
if (stepContent) { stepContent.classList.add('step-active'); }
if (activeStep === 2) {
document.getElementById('feedback-message').textContent = document.getElementById('feedback-text').value;
}
}
return !!isCurrentStepValid;
}
function setValidState(stepIndexToValidate) {
if (stepIndexToValidate === 0) {
var emailInput = document.getElementById('add-email');
window.onInputChange(emailInput, true);
isCurrentStepValid = emailInput.value.length && isEmailValid;
}
if (stepIndexToValidate === 1) {
var radioInputs = document.querySelectorAll('.survey-question input');
var isChecked = Array.from(radioInputs).some(function (input) { return input.checked; });
window.onInputChange(document.getElementById('feedback-text'));
isCurrentStepValid = isChecked && isFeedbackTextValid;
}
if (stepIndexToValidate === 2) { isCurrentStepValid = true; }
validationStepper.setValid(stepIndexToValidate, !!isCurrentStepValid);
}
</script>
<script>
(function (window, document) {
'use strict';
var root = document.getElementById('stepperValidation');
if (!root) { return; }
var message = document.getElementById('stepperMessage');
var checks = [
function () { return document.getElementById('stepName').value.trim().length > 0 ? '' : 'Enter a name.'; },
function () { return /^[^@\s]+@[^@\s]+$/.test(document.getElementById('stepEmail').value.trim()) ? '' : 'Enter an email with an @.'; },
function () { return ''; }
];
function show(index) {
Array.prototype.forEach.call(root.querySelectorAll('[data-step-panel]'), function (panel) {
panel.hidden = Number(panel.getAttribute('data-step-panel')) !== index;
});
}
root.addEventListener('click', function (e) {
var button = e.target.closest('[data-stepper-validate]');
if (!button) { return; }
var control = window.Lumen.get('validationStepper');
if (!control) { window.NavigationSampleLog('Control is not ready'); return; }
var index = control.getActiveStep();
if (button.getAttribute('data-stepper-validate') === 'previous') {
control.previous();
show(control.getActiveStep());
message.textContent = '';
return;
}
var problem = checks[index]();
control.setValid(index, problem === '');
message.textContent = problem || (index === 2 ? 'Finished.' : '');
if (problem === '') {
if (index < 2) { control.next(); show(control.getActiveStep()); }
window.NavigationSampleLog('Step ' + (index + 1) + ' is valid');
} else {
window.NavigationSampleLog('Step ' + (index + 1) + ' is invalid: ' + problem);
}
});
})(window, document);
</script>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using Lumen.UI.Mvc;
namespace YourApp.Controllers
{
public class StepperController : Controller
{
// The page is Views/Stepper/Validation.cshtml; it draws what ViewData holds.
public ActionResult Validation()
{
List<UiStep> stepperWithText = new List<UiStep>();
stepperWithText.Add(new UiStep { IconCss = "sf-icon-survey-intro", Label = "Survey Introduction" });
stepperWithText.Add(new UiStep { IconCss = "sf-icon-survey-feedback", Label = "Feedback" });
stepperWithText.Add(new UiStep { IconCss = "sf-icon-survey-status", Label = "Status" });
ViewData["StepperWithText"] = stepperWithText;
return View();
}
}
}
@* Install once: Install-Package Lumen.UI.Mvc (or: dotnet add package Lumen.UI.Mvc) *@
@* Views/Web.config: <add namespace="Lumen.UI.Mvc" /> *@
@* Views/Shared/_Layout.cshtml *@
<head>
@Html.UiStyles()
<link rel="stylesheet" href="~/Content/site.css" />
</head>
<body>
@RenderBody()
@Html.UiScripts()
@RenderSection("scripts", required: false)
</body>
This example demonstrates using the IsValid property for validating the state of each step within the Stepper. Stepper validation ensures that user inputs are correct and guides them to prevent errors before proceeding to the next steps.