Teodoris
Teodoris

Reputation: 109

How to add required field in MVC3 ? (Not using Model)

I want to add a required field validation on textboxes, I'm not using any model parameters(Annotations) for these textboxes. How to achieve this?

Following is my code:

@using (Html.BeginForm())
{
  <h1> 3D Pay Örnek Sayfa</h1>
  <table class="tableClass">
  <tr class="trHeader">
    <td>Test</td>
    <td>@Html.TextBox("TestIt")</td>
  </tr>
  </table>
}

Upvotes: 0

Views: 3737

Answers (2)

David_001
David_001

Reputation: 5812

Well, you really should use a model, but if you insist doing things by hand, I'd still recommend using the jquery validation plugin.

An example based on http://docs.jquery.com/Plugins/Validation#Example:

(Note: the bit you're looking for is @Html.TextBox("TestIt", "", new { @class="required" }), which add the class="required" attribute to the textbox, which in turn tells jquery validate that it's a required field.)

<html>
<head>
    <script src="http://code.jquery.com/jquery-latest.js"></script>
    <script type="text/javascript" src="http://jzaefferer.github.com/jquery-validation/jquery.validate.js"></script>
    <style type="text/css">
        * { font-family: Verdana; font-size: 96%; }
        label { width: 10em; float: left; }
        label.error { float: none; color: red; padding-left: .5em; vertical-align: top; }
        p { clear: both; }
        .submit { margin-left: 12em; }
        em { font-weight: bold; padding-right: 1em; vertical-align: top; }
    </style>
    <script>
        $(document).ready(function(){
           $("form").validate();
        });
    </script>
</head>
<body>
@using (Html.BeginForm())  
{  
    <center>  
        <h1> 3D Pay Örnek Sayfa</h1>  
            <table class="tableClass">  
                <tr class="trHeader">  

                    <td>Test</td>  
                    <td>@Html.TextBox("TestIt", "", new { @class="required" })</td>  
                </tr>  
            </table>  
    </center>  
    <input type="submit" id="SubmitData" name="SubmitData" value="Submit" />
}
</body>
</html>

Please remember this is just client side validation - you also need to validate on the server side too. As you're not using a model, this will probably mean some custom controller code to validate each input.

Upvotes: 3

jrummell
jrummell

Reputation: 43087

Even though you said you're not using a model, I would strongly recommend using a model.

Model:

public class TestModel
{
    [Required]
    public string TestIt {get; set;}
}

Markup:

@Html.TextBoxFor(m => m.TestIt)
@Html.ValidationMessageFor(m => m.TestIt)

See How to: Validate Model Data Using DataAnnotations Attributes for more information.

If you are dead set on not using a model, you could validate client side with jQuery Validate, but it will require more code.

Upvotes: 2

Related Questions