40
loading...
This website collects cookies to deliver better user experience
using System.ComponentModel.DataAnnotations;
namespace BlazorFormsValidation.Shared.Models
{
public class StudentRegistration
{
[Required]
[Display(Name = "First Name")]
public string FirstName { get; set; }
[Required]
[Display(Name = "Last Name")]
public string LastName { get; set; }
[Required]
[EmailAddress]
public string Email { get; set; }
[Required]
public string Username { get; set; }
[Required]
[RegularExpression(@"^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9]).{8,}$",
ErrorMessage = "Password should have minimum 8 characters, at least 1 uppercase letter, 1 lowercase letter and 1 number.")]
public string Password { get; set; }
[Required]
[Display(Name = "Confirm Password")]
[Compare("Password", ErrorMessage = "The password and confirm password fields do not match.")]
public string ConfirmPassword { get; set; }
[Required]
public string Gender { get; set; }
}
}
using System.ComponentModel.DataAnnotations;
namespace BlazorFormsValidation.Shared.Models
{
class UserNameValidation : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (!value.ToString().ToLower().Contains("admin"))
{
return null;
}
return new ValidationResult("The UserName cannot contain the word admin",
new[] { validationContext.MemberName });
}
}
}
public class StudentRegistration
{
// Other properties
[Required]
[UserNameValidation]
public string Username { get; set; }
// Other properties
}
The Add New Item dialog box will appear. Select the Visual C# option from the left panel. Then, select the API Controller-Empty option from the templates panel and provide the name StudentController.cs. Click Add.
Refer to the following image.
Then, include the following code inside the controller.
using BlazorFormsValidation.Shared.Models;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
namespace BlazorFormsValidation.Server.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class StudentController : ControllerBase
{
readonly List<string> userNameList = new();
public StudentController()
{
userNameList.Add("ankit");
userNameList.Add("vaibhav");
userNameList.Add("priya");
}
[HttpPost]
public IActionResult Post(StudentRegistration registrationData)
{
if (userNameList.Contains(registrationData.Username.ToLower()))
{
ModelState.AddModelError(nameof(registrationData.Username), "This User Name is not available.");
return BadRequest(ModelState);
}
else
{
return Ok(ModelState);
}
}
}
}
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Forms;
using System;
using System.Collections.Generic;
namespace BlazorFormsValidation.Client.Shared
{
public class CustomFormValidator : ComponentBase
{
private ValidationMessageStore validationMessageStore;
[CascadingParameter]
private EditContext CurrentEditContext { get; set; }
protected override void OnInitialized()
{
if (CurrentEditContext == null)
{
throw new InvalidOperationException(
$"{nameof(CustomFormValidator)} requires a cascading parameter of type {nameof(EditContext)}.");
}
validationMessageStore = new ValidationMessageStore(CurrentEditContext);
CurrentEditContext.OnValidationRequested += (s, e) =>
validationMessageStore.Clear();
CurrentEditContext.OnFieldChanged += (s, e) =>
validationMessageStore.Clear(e.FieldIdentifier);
}
public void DisplayFormErrors(Dictionary<string, List<string>> errors)
{
foreach (var err in errors)
{
validationMessageStore.Add(CurrentEditContext.Field(err.Key), err.Value);
}
CurrentEditContext.NotifyValidationStateChanged();
}
public void ClearFormErrors()
{
validationMessageStore.Clear();
CurrentEditContext.NotifyValidationStateChanged();
}
}
}
using BlazorFormsValidation.Client.Shared;
using BlazorFormsValidation.Shared.Models;
using Microsoft.AspNetCore.Components;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Json;
using System.Threading.Tasks;
namespace BlazorFormsValidation.Client.Pages
{
public class RegistrationModalBase : ComponentBase
{
[Inject]
HttpClient Http { get; set; }
[Inject]
ILogger<StudentRegistration> Logger { get; set; }
protected StudentRegistration registration = new();
protected CustomFormValidator customFormValidator;
protected bool isRegistrationSuccess = false;
protected async Task RegisterStudent()
{
customFormValidator.ClearFormErrors();
isRegistrationSuccess = false;
try
{
var response = await Http.PostAsJsonAsync("api/Student", registration);
var errors = await response.Content.ReadFromJsonAsync<Dictionary<string, List<string>>>();
if (response.StatusCode == HttpStatusCode.BadRequest && errors.Count > 0)
{
customFormValidator.DisplayFormErrors(errors);
throw new HttpRequestException($"Validation failed. Status Code: {response.StatusCode}");
}
else
{
isRegistrationSuccess = true;
Logger.LogInformation("The registration is successful");
}
}
catch (Exception ex)
{
Logger.LogError(ex.Message);
}
}
}
}
@page "/register"
@inherits RegistrationModalBase
<div class="row justify-content-center">
<div class="col-md-10">
<div class="card mt-3 mb-3">
<div class="card-header">
<h2>Student Registration</h2>
</div>
<div class="card-body">
@if (isRegistrationSuccess)
{
<div class="alert alert-success" role="alert">Registration successful</div>
}
<EditForm Model="@registration" OnValidSubmit="RegisterStudent">
<DataAnnotationsValidator />
<CustomFormValidator @ref="customFormValidator" />
<div class="form-group row">
<label class="control-label col-md-12">First Name</label>
<div class="col">
<InputText class="form-control" @bind-Value="registration.FirstName" />
<ValidationMessage For="@(() => registration.FirstName)" />
</div>
</div>
<div class="form-group row">
<label class="control-label col-md-12">Last Name</label>
<div class="col">
<InputText class="form-control" @bind-Value="registration.LastName" />
<ValidationMessage For="@(() => registration.LastName)" />
</div>
</div>
<div class="form-group row">
<label class="control-label col-md-12">Email</label>
<div class="col">
<InputText class="form-control" @bind-Value="registration.Email" />
<ValidationMessage For="@(() => registration.Email)" />
</div>
</div>
<div class="form-group row">
<label class="control-label col-md-12">User Name</label>
<div class="col">
<InputText class="form-control" @bind-Value="registration.Username" />
<ValidationMessage For="@(() => registration.Username)" />
</div>
</div>
<div class="form-group row">
<label class="control-label col-md-12">Password</label>
<div class="col">
<InputText type="password" class="form-control" @bind-Value="registration.Password"></InputText>
<ValidationMessage For="@(() => registration.Password)" />
</div>
</div>
<div class="form-group row">
<label class="control-label col-md-12">Confirm Password</label>
<div class="col">
<InputText type="password" class="form-control" @bind-Value="registration.ConfirmPassword"></InputText>
<ValidationMessage For="@(() => registration.ConfirmPassword)" />
</div>
</div>
<div class="form-group row">
<label class="control-label col-md-12">Gender</label>
<div class="col">
<InputSelect class="form-control" @bind-Value="registration.Gender">
<option value="-- Select City --">-- Select Gender --</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
</InputSelect>
<ValidationMessage For="@(() => registration.Gender)" />
</div>
</div>
<div class="form-group" align="right">
<button type="submit" class="btn btn-success">Register</button>
</div>
</EditForm>
</div>
</div>
</div>
</div>
<li class="nav-item px-3">
<NavLink class="nav-link" href="register">
<span class="oi oi-list-rich" aria-hidden="true"></span> Register
</NavLink>
</li>