https://github.com/drualcman/editformdemo.validation
Manual validation in Blazor EditForm component
https://github.com/drualcman/editformdemo.validation
blazor blazor-server blazor-webassembly
Last synced: about 2 months ago
JSON representation
Manual validation in Blazor EditForm component
- Host: GitHub
- URL: https://github.com/drualcman/editformdemo.validation
- Owner: drualcman
- License: mit
- Created: 2023-07-16T09:14:09.000Z (almost 3 years ago)
- Default Branch: master
- Last Pushed: 2025-05-25T03:42:04.000Z (about 1 year ago)
- Last Synced: 2025-10-06T09:55:54.213Z (9 months ago)
- Topics: blazor, blazor-server, blazor-webassembly
- Language: C#
- Homepage: https://aprende-a-programar.com/b/Como-validar-un-formulario-manualmente-en-Blazor-Server-o-WebAssembly/
- Size: 17.6 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE.txt
Awesome Lists containing this project
README
# Manual validation EditForm Component Demo
This project it�s a simple example how to validate a model when you don�t have access to the model code.
## Scenario
* The class ```ExampleModelFromExternalDll``` represent a exterdal model we can't modify.
* We will manually validate some properties
* Must be show a validation error messages
* When is validated can send the form
### Example
Component
``` RAZOR
First Name
Email
Submit
@Messages
```
Code
``` CSHARP
string Messages;
ExampleModelFromExternalDll Model = new();
EditContext FormContext;
ValidationMessageStore ValidationMessageStore;
protected override void OnInitialized()
{
FormContext = new EditContext(Model);
FormContext.OnFieldChanged += FormContext_OnFieldChanged;
FormContext.OnValidationRequested += FormContext_OnValidationRequested;
ValidationMessageStore = new ValidationMessageStore(FormContext);
}
private void FormContext_OnValidationRequested(object sender, ValidationRequestedEventArgs e)
{
Messages = "";
ValidationMessageStore.Clear();
if(string.IsNullOrWhiteSpace(Model.FirstName))
ValidationMessageStore.Add(new FieldIdentifier(Model, nameof(Model.FirstName)), "First name required");
if(string.IsNullOrWhiteSpace(Model.Email))
ValidationMessageStore.Add(new FieldIdentifier(Model, nameof(Model.Email)), "Email required");
FormContext.NotifyValidationStateChanged();
}
private void FormContext_OnFieldChanged(object sender, FieldChangedEventArgs e)
{
Messages = "";
ValidationMessageStore.Clear(e.FieldIdentifier);
switch(e.FieldIdentifier.FieldName)
{
case nameof(Model.FirstName):
if(string.IsNullOrWhiteSpace(Model.FirstName))
ValidationMessageStore.Add(e.FieldIdentifier, "First name required");
break;
case nameof(Model.Email):
if(string.IsNullOrWhiteSpace(Model.Email))
ValidationMessageStore.Add(e.FieldIdentifier, "Email required");
if(!Model.Email.Contains("@"))
ValidationMessageStore.Add(e.FieldIdentifier, "Email not valid");
break;
}
FormContext.NotifyValidationStateChanged();
}
void SubmitForm()
{
Messages = "Form will be send!";
}
```