Hi Team
I need some help, my customValidation does not work and when i debug its showing any error. Please assist mates, basically the logic i want when leaving the [email protected](). Must validate message error "This field is required".
- // Model class
- [Required(ErrorMessage = "This field is required")]
- [DataType(DataType.PhoneNumber)]
- public string CellNumber { get; set; }
- // CustomValidation.cs
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using eNtsaRegistrationTraining.Models;
- using System.ComponentModel.DataAnnotations;
- namespace eNtsaRegistrationTraining.CustomValidation
- {
- public class CustomFormValidation:ValidationAttribute
- {
- protected override ValidationResult IsValid(object value, ValidationContext validationContext)
- {
- var registration = (TrainingRegForm)validationContext.ObjectInstance;
- if(registration.CellNumber==null)
- {
- return new ValidationResult("This field is required");
- }
- return base.IsValid(value, validationContext);
- }
- }
- }
- // Controller.
- //GET:TrainingRegForm/Create/WebRequest.
- [HttpPost]
- [ValidateAntiForgeryToken]
- public ActionResult SubmitRegDetails([Bind(Include= "Id, Title, FirstName, LastName, Position, Company, StreetAddress, StreetAddressLine, City, StateProvince, ZipCode,Email, CellNumber, DietaryRequirement")]TrainingRegForm eNtsaTraining)
- {
- if(ModelState.IsValid)
- {
- eNtsaTraining.Id = Guid.NewGuid();
- db.TrainingRegs.Add(eNtsaTraining);
- db.SaveChanges();
- return RedirectToAction("SaveRegForm");
- }
- // Validates when empty.
- if(ModelState.IsValid)
- {
- return RedirectToAction("SaveRegForm");
- }
- return View(eNtsaTraining);
- }
- // View
- div class="form-group row">
- ="Attendee" class="col-sm-2 col-form-label">Attendee Cell Number*
- class="col-sm-3">
- @Html.EditorFor(model => model.RegForm.CellNumber, new { htmlAttributes = new { @class = "form-control", autofocus = "autofocus", placeholder = "Cell Number" } })
- @Html.ValidationMessageFor(model => model.RegForm.CellNumber, "", new { @class = "text-danger" })
Guest UserPosted Jul 1, 2020, 6:23 AM
Farhan AhmedPosted Jun 30, 2020, 1:41 AM