Articles → ASP.NET CORE → Validations In Asp.Net Core

Validations In Asp.Net Core






Scenario





Steps For Validation




  1. Create an entity and apply "Required" attribute over the property.
  2. Apply "asp-validation-summary" on the div tag.
  3. Add the span with the "asp-validation-for" attribute.

Code




using System.ComponentModel.DataAnnotations;

namespace BookManagementSystem.Model {
  public class Book {
    [Key]
    public int Id {
      get;
      set;
    }

    [Required]
    public string Name {
      get;
      set;
    }

    public string Author {
      get;
      set;
    }
  }
}




@page
@model BookManagementSystem.Pages.Books.CreateModel

<div class="border container" style="padding:30px">
	<form method="post">
		<div class="text-danger" asp-validation-summary="ModelOnly"></div>
		<div class="form-group row">
			<div class="col-3">
				<label asp-for="MyBook.Name"></label>
			</div>
			<div class="col-5">
				<input asp-for="MyBook.Name" class="form-control" />
			</div>
			<div class="col-4">
				<span asp-validation-for="MyBook.Name" class="text-danger"></span>
			</div>
		</div>
		<div class="form-group row">
			<div class="col-3">
				<label asp-for="MyBook.Author"></label>
			</div>
			<div class="col-5">
				<input asp-for="MyBook.Author" class="form-control" />
			</div>
			<div class="col-4">
				<span asp-validation-for="MyBook.Author" class="text-danger"></span>
			</div>
		</div>
		<div class="form-group row">
			<div class="col-4">
				<input type="submit" value="Create" class="btn btn-primary form-control" />
			</div>
		</div>
	</form>
</div>

@section Scripts{ 
    
<partial name="_ValidationScriptsPartial" />
}





Output


Picture showing validations in asp.net core
Click to Enlarge


Posted By  -  Karan Gupta
 
Posted On  -  Thursday, April 1, 2021

Query/Feedback


Your Email Id
 
Subject
 
Query/FeedbackCharacters remaining 250