1

while I was working with validation in MVC, and I wrote a custom attribute to validate a property.Initially the client side validation was not working since attribute was not registered.When i clicked on the save button after contacting the server it was showing the error message.So can anyone tell how this server side validation took place instead of client side validation ?

attribute usage ->

[PhoneNumberHasPlus(ErrorMessage="Invalid number")]
public string PhoneNumber {get;set;}

attribute ->

 public class PhoneNumberHasPlusAttribute : RegularExpressionAttribute
    {
        public PhoneNumberHasPlusAttribute() :
            base(@"^[+][0-9' '\.\-\(\)]{10,20}$") { }

        public override string FormatErrorMessage(string name)
        {
            if (String.IsNullOrEmpty(ErrorMessage))
                ErrorMessage = "PhoneNumberWithPlus";
            return ErrorMessage;
        }
    }
Necromancer
  • 194
  • 3
  • 13

2 Answers2

0

You have to have a Model.IsValid in your action. That element turns on the validation.

public ActionResult Create(Model model) {
    if (ModelState.IsValid) {
        // logic
    } 
    return View(dinner); 
}

Please make sure that your view contains correct path to jQuery libraries

<script src="@Url.Content("~/Scripts/jquery.validate.min.js")"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")"></script>

Also your have to use this Razor syntax to generate correct html

@Html.EditorFor(model => model.ReleaseDate)
@Html.ValidationMessageFor(model => model.ReleaseDate)

Here you can find a full tutorial of adding validation to the MVC Model.

Lukasz Pyrzyk
  • 418
  • 4
  • 9
0

You need to include jquery Val bundle into your view like this

@section scripts
{
    @Scripts.Render("~/bundles/jqueryVal")
}