TECHNOLOGIES
FORUMS
JOBS
BOOKS
EVENTS
INTERVIEWS
Live
MORE
LEARN
Training
CAREER
MEMBERS
VIDEOS
NEWS
BLOGS
Sign Up
Login
No unread comment.
View All Comments
No unread message.
View All Messages
No unread notification.
View All Notifications
Answers
Post
An Article
A Blog
A News
A Video
An EBook
An Interview Question
Ask Question
Forums
Monthly Leaders
Forum guidelines
Guest User
Tech Writer
2.1k
474.1k
CustomValidation not working on asp.net mvc form?
Jun 29 2020 3:06 PM
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"
>
<label
for
=
"Attendee"
class
=
"col-sm-2 col-form-label"
>Attendee Cell Number*</label>
<div
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"
})
</div>
</div>
Reply
Answers (
2
)
A question on skills required to be an ASP.NET developer
Why i am getting error Cannot set property 'value' of null