Shawn Mclean
Shawn Mclean

Reputation: 57469

Manually add validation to textbox without a model

I have a single textbox in a form that I would like to add some validation to.

How can I add some unobtrusive validation attributes to it without using a model?

For eg.

    @using (Html.BeginForm())
    {
        @Html.ValidationSummary()
        @Html.Label("code", "Confirmation Code") 
        @Html.TextBox("code")<!-- I want validation on this thing -->
        <input type="submit" value="Go" />
    }   

How can I make it required, and others such as stringlength, etc.

Upvotes: 5

Views: 4582

Answers (3)

Piotr Kula
Piotr Kula

Reputation: 9841

Based on David's link to Brad Wilson and some of my own digging around this is the solution

<input id="MyInput" name="MyInput" data-val="true" data-val-required="The Error Message"></input>
<span class="field-validation-error" data-valmsg-for="MyInput" data-valmsg-replace="true"></span>

The input requries data-val="true" to be enabled.

Then you add the requirements. You can inspect validators by using the normal Helper in MVC to learn the ones you want.

For example:

 data-val-required="Message for requires"

 data-val-length-min="5"
 data-val-length="The message for min length 5"

And that will unobtrusively validate your form. (as long as you got the jquery.unobtrisive.validate included and not the normal one)

Upvotes: 1

Igor Gayevoy
Igor Gayevoy

Reputation: 24

Maybe it's too late but I just found a solution.

var metaInfo = ViewData.ModelMetadata.Properties.First(data => data.PropertyName == "[Property name]");

Dictionary<string, object> attributes = new Dictionary<string, object>();

var validators = metaInfo.GetValidators(ViewContext.Controller.ControllerContext);
if(validators.Count() > 0)
{
    attributes.Add("data-val", "true");
    foreach (var validator in validators)
    {
        foreach(var rule in validator.GetClientValidationRules())
        {
            attributes.Add(string.Format("data-val-{0}", rule.ValidationType), rule.ErrorMessage);
            foreach(var param in rule.ValidationParameters)
            {
                attributes.Add(string.Format("data-val-{0}-{1}", rule.ValidationType, param.Key), param.Value);
            }
        }
    }
}

Upvotes: 1

David Glenn
David Glenn

Reputation: 24532

HtmlHelpers will render HTML elements that contain a data-* attribute that contain all the data that the unobtrusive JavaScript uses to perform the client validation.

I'm not aware of any resources documenting the data-* HTML attributes so I would suggest creating a simple temporary model decorated with the required Data Annotations and viewing the rendered HTML.

Once you know the HTML attributes required then you can render them directly in your HTML.

Update

This Brad Wilson post may help

Upvotes: 2

Related Questions