使用 xVal 验证标题和用户名的唯一组合

发布于 2024-08-13 16:17:09 字数 2646 浏览 5 评论 0原文

我有一个用于创建/编辑文章的表单。每篇文章都与一个用户相关联。

文章发布后,每篇文章的链接都由用户名和文章标题组成({userName}/{articleTitle} 应该是唯一的组合):

/articles/{userName}/{articleTitle}

文章类:

public class Article
{
    public int ArticleId { get; set; }

    [Required(ErrorMessage = "Please enter title")]
    public string Title { get; set; }         

    [Required(ErrorMessage = "Please select a user")]
    public int UserId { get; set; }        
}

视图模型:

public class ArticleFormViewModel
{
    public Article Article { get; set; }
    public SelectList Users { get; set; }

    public ArticleFormViewModel(Article article, Dictionary<int, string> allUsers)
    {
        Article = article;

        List<SelectListItem> list = new List<SelectListItem>();
        list.Add(new SelectListItem() { Value = "", Text = "Please select a user" });

        foreach (var user in allUsers)
        {
            list.Add(new SelectListItem() { Value = user.Key.ToString(), Text = user.Value });
        }

        Users = new SelectList(list, "Value", "Text", Article.UserId);
    }
}

视图:

<div id="validationSummary">
    <%= Html.ValidationSummary("Please correct the errors and try again.") %>
</div>

<% using (Html.BeginForm()) {%>               
    <%= Html.Hidden("ArticleId", Model.Article.ArticleId) %>

    <fieldset>
    <legend>Article</legend>            
    <ul>
        <li>
            <label for="UserId">User: <%= Html.ValidationMessage("UserId", "*")%></label>
            <%= Html.DropDownList("UserId", Model.Users) %>
        </li>
        <li>
            <label for="Title">Title: <%= Html.ValidationMessage("Title", "*") %></label>
            <%= Html.TextBox("Title", Model.Article.Title) %>
        </li>            
    </ul>
    <input type="submit" value="Save" />            
    </fieldset>
<% } %>

<%= Html.ClientSideValidation(typeof(Article))
                .AddRule("Title", new RemoteRule(Url.Action("ValidateTitle")))
                .UseValidationSummary("validationSummary", "Please correct the errors and try again.")%> 

我使用 xVal 进行验证。

ValidateTitle - 是一个控制器操作,用于验证 {userName}/{articleTitle} 是否唯一。它使用 Ajax 工作。

当我编辑标题时,一切正常,但当我更改选择列表中的用户时,我遇到了问题。如果用户 1 的标题无效,并且我选择用户 2,则之前的错误消息仍然存在,并且我无法检查用户 2 的标题是否有效。

我可以像使用标题一样验证用户名,但有时会显示 2 个错误,表明用户名和标题组合无效。

标题错误和用户错误应该同步,但是如何同步呢?

或者也许我应该使用另一种方式来处理标题和用户列表?

I have a form for create/edit articles. Every article is associated with an user.

After article is publshed the link to each article is composed from user name and article title (and {userName}/{articleTitle} should be unique combination):

/articles/{userName}/{articleTitle}

Article class:

public class Article
{
    public int ArticleId { get; set; }

    [Required(ErrorMessage = "Please enter title")]
    public string Title { get; set; }         

    [Required(ErrorMessage = "Please select a user")]
    public int UserId { get; set; }        
}

View model:

public class ArticleFormViewModel
{
    public Article Article { get; set; }
    public SelectList Users { get; set; }

    public ArticleFormViewModel(Article article, Dictionary<int, string> allUsers)
    {
        Article = article;

        List<SelectListItem> list = new List<SelectListItem>();
        list.Add(new SelectListItem() { Value = "", Text = "Please select a user" });

        foreach (var user in allUsers)
        {
            list.Add(new SelectListItem() { Value = user.Key.ToString(), Text = user.Value });
        }

        Users = new SelectList(list, "Value", "Text", Article.UserId);
    }
}

View:

<div id="validationSummary">
    <%= Html.ValidationSummary("Please correct the errors and try again.") %>
</div>

<% using (Html.BeginForm()) {%>               
    <%= Html.Hidden("ArticleId", Model.Article.ArticleId) %>

    <fieldset>
    <legend>Article</legend>            
    <ul>
        <li>
            <label for="UserId">User: <%= Html.ValidationMessage("UserId", "*")%></label>
            <%= Html.DropDownList("UserId", Model.Users) %>
        </li>
        <li>
            <label for="Title">Title: <%= Html.ValidationMessage("Title", "*") %></label>
            <%= Html.TextBox("Title", Model.Article.Title) %>
        </li>            
    </ul>
    <input type="submit" value="Save" />            
    </fieldset>
<% } %>

<%= Html.ClientSideValidation(typeof(Article))
                .AddRule("Title", new RemoteRule(Url.Action("ValidateTitle")))
                .UseValidationSummary("validationSummary", "Please correct the errors and try again.")%> 

I'm using xVal for validation.

ValidateTitle - is a controller action which validates that {userName}/{articleTitle} is unique. It works using Ajax.

Everything works fine when I'm editing title, but I have problems when I change the user in select list. If title was invalid for user1, and I choose user2, previous error message remains and I can't check that title for user2 is valid.

I can validate user name the same way I do it with title, but there will be cases when 2 errors saying that user name and title combination is invalid will be shown.

Title errors and user errors should be synchronized, but how?

Or maybe there is another way I should work with title and users list?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

故事灯 2024-08-20 16:17:09

xVal 生成验证规则(用于 jQuery 验证插件):

<script type="text/javascript">xVal.AttachValidator(null, 
{"Fields":[{"FieldName":"ArticleId","FieldRules":[{"RuleName":"DataType","RuleParameters":{"Type":"Integer"}}]},
{"FieldName":"Title","FieldRules":[{"RuleName":"Required","RuleParameters":{},"Message":"Please enter title"}, 
{"RuleName":"Remote","RuleParameters":{"url":"/articles/ValidateTitle"}}]},
{"FieldName":"UserId","FieldRules":[{"RuleName":"Required","RuleParameters":{},"Message":"Please select a user"}]}]}, 
{"ValidationSummary":{"ElementID":"validationSummary","HeaderMessage":"Please correct the errors and try again."}})</script>  

现在只有一个条件:应从选择列表中选择用户。

当 title + user1 无效并且我从列表中选择 user2 时,我不知道如何隐藏(重置)标题错误消息。

相反:在选择用户并编辑标题后隐藏用户错误消息。

xVal generates validation rules (for jQuery validation plug-in):

<script type="text/javascript">xVal.AttachValidator(null, 
{"Fields":[{"FieldName":"ArticleId","FieldRules":[{"RuleName":"DataType","RuleParameters":{"Type":"Integer"}}]},
{"FieldName":"Title","FieldRules":[{"RuleName":"Required","RuleParameters":{},"Message":"Please enter title"}, 
{"RuleName":"Remote","RuleParameters":{"url":"/articles/ValidateTitle"}}]},
{"FieldName":"UserId","FieldRules":[{"RuleName":"Required","RuleParameters":{},"Message":"Please select a user"}]}]}, 
{"ValidationSummary":{"ElementID":"validationSummary","HeaderMessage":"Please correct the errors and try again."}})</script>  

Now there is only one condition: a user should be chosen from select list.

I don't know how to hide (reset) title error message when title + user1 is invalid and I chose user2 from list.

And opposite: hide user error message after I chose user and edit title.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文