Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • Rune Grønkjær 1372 posts 3103 karma points MVP
    Apr 10, 2013 @ 16:35
    Rune Grønkjær
    0

    Razor check if field is valid

    Hi Guys,

    I want to add an "error" class to my markup whenever a field is invalid. In the Form.cshtml file I have the field foreach loop, and access to a lot of information. Only thing I cant find is a property or something to show me if the field is actually invalid. The validation message is written like this by standard:

    @if (Model.ShowFieldValidaton){@Html.ValidationMessage(f.Id)}

    That's the only place that a "real" validation is made and it's kind of cheat, as it just returns som html.

    Can I somehow get a true/false instead?

    /Rune

  • Comment author was deleted

    Apr 15, 2013 @ 11:05

    Hmm maybe it's better to look into adding this to the jquery validate stuff, think that has some hooks you can use

  • Comment author was deleted

    Apr 15, 2013 @ 11:07

    Or try to access ModelState["Name"].Errors.Count() > 0

  • Rune Grønkjær 1372 posts 3103 karma points MVP
    Apr 17, 2013 @ 11:55
    Rune Grønkjær
    0

    Hi Tim,

    There's no ModelState in Form.cshtml. Problem is that the FieldViewModel object contains no information about errors.

    About the jQuery Validate plugin, it would work without hooks or anything if I could:

    1. Add a required="required" attribute to the fields
    2. Add an "error" class to the field if it does not validate correctly

    Both should be done serverside, but I can't figure out what FieldViewModel properties I should use.

    /Rune

  • Comment author was deleted

    Apr 17, 2013 @ 12:06

    Ok will check what I can do about that

  • Comment author was deleted

    Apr 22, 2013 @ 10:01

    Hi Rune,

    Just tested and you should be able to use

    in fieldtype view:

     @if (ViewData.ModelState[Model.Name] != null)

    {

        @ViewData.ModelState[Model.Name].Errors.Count()

    }

    in form view (field loop)

     if (ViewData.ModelState[f.Name] != null)

     {

                                     @ViewData.ModelState[f.Name].Errors.Count()

     }

     

  • Rune Grønkjær 1372 posts 3103 karma points MVP
    Apr 22, 2013 @ 10:33
    Rune Grønkjær
    0

    Perfect. That worked just like I wanted it.

    Thanks a lot Tim.

    /Rune

  • Comment author was deleted

    Apr 22, 2013 @ 11:13

    Great :)

  • This forum is in read-only mode while we transition to the new forum.

    You can continue this topic on the new forum by tapping the "Continue discussion" link below.

Please Sign in or register to post replies