"要求"验证属性不是在asp.net mvc的3个工作,而其他工作 [英] "Required" validation attribute not working in asp.net mvc 3 while others work

查看:81
本文介绍了"要求"验证属性不是在asp.net mvc的3个工作,而其他工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在那里我已经创建了一个单独的验证类我的实体对象一个奇怪的情况:

  [MetadataType(typeof运算(TopTenFav_Validation))]
公共部分类TopTenFav
{}
公共类TopTenFav_Validation
{    [必需(的ErrorMessage =Youtube链接是必需)]
    [StringLength(100的ErrorMessage =Youtube链接不能超过100个字符)]
    [范围(10,20)
    公共字符串YoutubeLink {搞定;组; }
    [StringLength(100的ErrorMessage =Youtube链接不能超过50个字符)]
    [需要]
    [MINLENGTH个(5,的ErrorMessage =Youtube链接不能少于30个字符)]
    公共字符串名称{搞定;组; }
}

实体对象的名字相同,我验证类 - TopTenFav,所以我红就会自动验证逻辑映射到我的实体框架的对象。我有一个小的形式,我映射到文本框模型如下:

 < D​​IV>
            @ Html.TextBoxFor(M = GT; m.topTenFav.YoutubeLink,新{ID =youTubeLinkTxt})
            @ Html.ValidationMessageFor(M => m.topTenFav.YoutubeLink,*)
        < / DIV>         < D​​IV>
            @ Html.TextBoxFor(M = GT; m.topTenFav.Title,新{ID =youTubeNameTxt})
             @ Html.ValidationMessageFor(M => m.topTenFav.Title,*)
        < / DIV>

问题是,所需的属性不工作,而其他工作,这意味着,当我离开文本框为空,我做一个AJAX调用服务器上的code传递的成功,但是当我在数据类型不通过的minLenght验证了code去我Ajax调用的错误部分如我所料。那么,我在这里缺少了必要的验证程序没有启动起来,当我的文本框是空的?

 的$(document)。在(点击,.btnAddTopTenFav功能(){
        VAR btnClicked = $(本);
        VAR txtLink = $('#youTubeLinkTxt)VAL()。
        VAR txtName的= $('#youTubeNameTxt)VAL()。
        VAR SUBLINK = txtLink.substr(31); //.replace(/.*\\?v=/,'');
        。VAR等级= $(本).parent()指数()+ 1;
        $(#hiddenRank)VAL(职级)。        $阿贾克斯({
            beforeSend:功能(){ShowAjaxLoader(); },
            网址:/首页/ AddTopTenFav /
            键入:POST,
            数据:$(#AddTopTenFavForm),序列化()。
            成功:功能(数据){HideAjaxLoader(),ShowMsg(首歌曲添加成功),$(btnClicked).replaceWith('< A NAME =+ SUBLINK +'级=savedLinks的href =# >'+ txtName的+'&下; / A>&下;跨度名='+资料+'类=btnDeleteTopTenFavSong dontDoAnything&X的催化剂&下; /跨度'); },
            错误:函数(){HideAjaxLoader(),ShowMsg(不能添加歌曲,请重试)}
        });
  [HttpPost]
    公众的ActionResult AddTopTenFav(HomeViewModel TOPTEN)
    {
        如果(ModelState.IsValid)
        {
            VAR顶部=新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(顶部);
            repository.Save();
            返回this.Content(top.SongId.ToString());
        }
        其他
        {
            返回查看();
        }


解决方案

的问题是,你是不是调用验证您发布之前发生。

MINLENGTH个验证器火,因为你将数据输入字段,然后离开它,它会调用该字段的验证。但是,要求校验器将仅当表单的提交事件调用,或火灾,如果你手动调用验证表单。

添加以下包裹在 $(文件)。对code(点击,.btnAddTopTenFav功能:

  $(形式)验证()形式();
如果($(形式)。有效的())
{
    //插入您的提交code的其余部分在这里
}

这将调用验证,如果表单是有效的将只能提交。

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();
        }

解决方案

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.

这篇关于&QUOT;要求&QUOT;验证属性不是在asp.net mvc的3个工作,而其他工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆