“Required” validation attribute not working in asp.net mvc 3 while others work

I have a weird situation where I have created a separate validation class for my Entity object:

   [MetadataType(typeof(TopTenFav_Validation))]
public partial class TopTenFav
{

}
public class TopTenFav_Validation
{

    [Required(ErrorMessage = "Youtube link is Required")]
    [StringLength(100, ErrorMessage="Youtube link cannot exceed 100 characters")]
    [Range(10,20)]
    public string YoutubeLink { get; set; }


    [StringLength(100, ErrorMessage = "Youtube link cannot exceed 50 characters")]
    [Required]
    [MinLength(5, ErrorMessage = "Youtube link cannot be shorter than 30 characters")]
    public string Title { get; set; }
}

The Entity object's name is the same as my validation class - TopTenFav, so as I red it should automatically map the validation logic to my Entity Framework objects. I have a little form where I mapped textboxes to the model as follows:

         <div>
            @Html.TextBoxFor(m => m.topTenFav.YoutubeLink, new { id = "youTubeLinkTxt"          })
            @Html.ValidationMessageFor(m => m.topTenFav.YoutubeLink,"*")
        </div>

         <div>
            @Html.TextBoxFor(m => m.topTenFav.Title, new { id = "youTubeNameTxt" })
             @Html.ValidationMessageFor(m => m.topTenFav.Title,"*")
        </div>

The problem is that the required attribute is not working while others work, meaning that when I leave the textboxes empty and I make an ajax call to the server the code passes on the success but when I type in data that doesnt pass the minLenght validator the code goes to the error part of my ajax call as I expected. So what am I missing here that the required validator is not firing up when my textboxes are empty?

    $(document).on("click", ".btnAddTopTenFav", function () {
        var btnClicked = $(this);
        var txtLink = $('#youTubeLinkTxt').val();
        var txtName = $('#youTubeNameTxt').val();
        var subLink = txtLink.substr(31); //.replace(/.*\?v=/, '');
        var rank = $(this).parent().index() + 1;
        $("#hiddenRank").val(rank);

        $.ajax({
            beforeSend: function () { ShowAjaxLoader(); },
            url: "/Home/AddTopTenFav/",
            type: "POST",
            data: $("#AddTopTenFavForm").serialize(),
            success: function (data) { HideAjaxLoader(), ShowMsg("Song Added Successfully"), $(btnClicked).replaceWith('<a name="' + subLink + '" class="savedLinks"  href="#" >' + txtName + '</a><span name=' + data + ' class="btnDeleteTopTenFavSong dontDoAnything">x</span'); },
            error: function () { HideAjaxLoader(), ShowMsg("Song could not be added, please try again") }
        });


  [HttpPost]
    public ActionResult AddTopTenFav(HomeViewModel topTen)
    {
        if (ModelState.IsValid)
        {
            var top = new TopTenFav();
            top.Date = DateTime.Now;
            top.Rank = topTen.topTenFav.Rank;
            top.UserName = User.Identity.Name;
            top.YoutubeLink = topTen.topTenFav.YoutubeLink;
            top.Title = topTen.topTenFav.Title;
            repository.AddTopTen(top);
            repository.Save();
            return this.Content(top.SongId.ToString());
        }
        else 
        {
            return View();
        }

Answers


The issue is that you are not invoking validation to occur before you are posting.

The MinLength validators fire, because you are entering data into the field, then leaving it, which invokes the validation for that field. However, the Required validators will only fire if invoked by the form's submit event, or if you manually invoke validation for the form.

Add the following to wrap the code in your $(document).on("click", ".btnAddTopTenFav" function:

$("form").validate().form();
if ($("form").valid())
{
    // insert the rest of your submission code here
}

This will invoke the validation, and will only submit if the form is valid.


Need Your Help

Maven archetype problem

maven maven-plugin maven-archetype

I am a newbie to maven. I have installed apache archiva in my machine to use as maven-proxy. My purpose is that I want to generate a sample project structure using maven archiva plugin. I have upl...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.