Adding error message and validation rule
GuestResponse.csusing System; using System.Collections.Generic; using System.Web; using System.ComponentModel.DataAnnotations; namespace MyFirstMVCApp.Models { public class GuestResponse { [Required(ErrorMessage = "Please enter your name")] public string Name { get; set; } [Required(ErrorMessage = "Please enter your email address")] [RegularExpression(".+\\@.+\\..+", ErrorMessage = "Please enter a valid email address")] public string Email { get; set; } [Required(ErrorMessage = "Please enter your phone number")] public string Phone { get; set; } [Required(ErrorMessage = "Please specify whether you'll attend")] public bool? WillAttend { get; set; } } }
HomeController.cs
[HttpPost] public ViewResult RsvpForm(GuestResponse guestResponse) { if (ModelState.IsValid) { // TODO: Email response to the party organizer return View("Thanks", guestResponse); } else { // there is a validation error return View(); } }
RsvpForm.cshtml
<head> <meta name="viewport" content="width=device-width" /> <title>RsvpForm</title> </head> <body> <div> @using (Html.BeginForm()) { @Html.ValidationSummary() <p> Your name: @Html.TextBoxFor(x => x.Name) </p> <p> Your email: @Html.TextBoxFor(x => x.Email)</p> <p> Your phone: @Html.TextBoxFor(x => x.Phone)</p> <p> Will you attend? @Html.DropDownListFor(x => x.WillAttend, new[] { new SelectListItem() { Text = "Yes, I'll be there", Value = bool.TrueString }, new SelectListItem() { Text = "No, I can't come", Value = bool.FalseString } }, "Choose an option") </p> <input type="submit" value="Submit RSVP" /> } </div> </body> </html>
Highlight Invalid Field
add this css style.field-validation-error {color: #f00;}
.field-validation-valid { display: none;}
.input-validation-error { border: 1px solid #f00; background-color: #fee; }
.validation-summary-errors { font-weight: bold; color: #f00;}
.validation-summary-valid { display: none;}
By Mohd Zulkamal
NOTE : – If You have Found this post Helpful, I will appreciate if you can Share it on Facebook, Twitter and Other Social Media Sites. Thanks =)
0 comments:
Post a Comment