using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using System.ComponentModel.DataAnnotations; namespace ASPLearner.Pages { public class IndexModel : PageModel { private readonly ILogger<IndexModel> _logger; public IndexModel(ILogger<IndexModel> logger) { _logger = logger; } //declare the fields to validate for the Name and Query //add the required attributes [Required(ErrorMessage = "The name field is required")] //the name field needs to be at least three characters long [StringLength(3,ErrorMessage ="Please enter a valid name")] public string Name { get;set; } //the query field cannot be empty [Required(ErrorMessage ="The query field cannot be empty")] //the query field needs to be at least 20 characters long [StringLength(20,ErrorMessage ="The query needs to be at least 20 characters long")] public string Query { get;set; } [Required(ErrorMessage ="The email field is required")] [StringLength(15,ErrorMessage ="Email Address to short")] //all emails need to conform to the email pattern [RegularExpression("^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$\r\n",ErrorMessage ="You entered an invalid Email Address")] public string Email { get; set; } public IActionResult OnPost() { //handle any invalid input in here if(!ModelState.IsValid) { return Page(); } return RedirectToPage("/Queries"); } } }
<form method="post" asp-route="Form" id="form"> <div class="form-group"> <label for="name">Name</label> <input type="text" name="Name" class="form-control" id="name" onchange="validate()"> <span asp-validation-for="Name" class="text-danger" id="vname"></span> </div> <div class="form-group"> <label for="email">Email</label> <input type="email" class="form-control" id="email" name="Email"/> <span asp-validation-for="Email" class="text-danger" id="vemail"></span> </div> <div class="form-group"> <label for="query">Query</label> <textarea class="form-control" name="Query" id="query" style="margin-top:10px"></textarea> <span asp-validation-for="Query" class="text-danger" id="vquery"></span> </div> </form>
\r\n
$
var
This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)