Validation in DotVVM
Validation in DotVVM is very similar to validation in ASP.Net MVC and ASP.Net Core.
You can validate your view model by using validation attributes. DotVVM does client side validation for only the following attributes:
- Required
- Compare
- EmailAddress
- Range
- RegularExporession
If the user input is not valid you have two controls you can use to show error messages:
- Validator Control
Shows error message against the target input control
- VaicationSummary Control
Shows the summary for all errors in your view model.
Straight Validation
Suppose we have a small registration form that requires the user to enter his/her name, gender, and age. All fields are required. To validate user's input we just need to annotate our viewmodel properties with Required attribute. Our ViewModel class will be like this:
- [Required(ErrorMessage = "Name is required")]
- public string Name { get; set; }
- public string Gender { get; set; }
- [Required(ErrorMessage = "Age is required")]
- public int? Age { get; set; }
In our view we will use only Validator control to show error messages.
- <dot:Literal class="control-label col-md-3" Text="Name"></dot:Literal>
- <dot:TextBox Text="{value: Name}" class="form-control" Type="Normal"></dot:TextBox>
- <dot:Validator HideWhenValid="true" Value="{value: Name}" ShowErrorMessageText="true"></dot:Validator>
- <br /><br />
- <dot:Literal class="control-label col-md-3" Text="Gender"></dot:Literal>
- <dot:RadioButton CheckedItem="{value: Gender}" CheckedValue="{value: "1"}" Text="Male"></dot:RadioButton>
- <dot:RadioButton CheckedItem="{value: Gender}" CheckedValue="{value: "2"}" Text="Female"></dot:RadioButton>
- <br /><br />
- <dot:Literal class="control-label col-md-3" Text="Age"></dot:Literal>
- <dot:TextBox Text="{value: Age}" class="form-control" Type="Number"></dot:TextBox>
- <dot:Validator HideWhenValid="true" Value="{value: Age}" ShowErrorMessageText="true"></dot:Validator>
- <br /><br />
- <dot:Button Click="{command: Save()}" Text="Save" class="btn btn-outline-secondary btn-sm"></dot:Button>

Join the conversation! Your thoughts help the community grow.