Manually add validation to a text box without a model

I have one text box on the form in which I would like to add some validation.

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

For instance,

    @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 do this requiredand others like stringlength etc.

+5
source share
3 answers

It may be too late, but I 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);
            }
        }
    }
}
+1
source

HtmlHelpers will display HTML elements containing an attribute data-*that contains all the data that unobtrusive JavaScript uses to perform client validation.

- , data-* HTML, , HTML.

, HTML, HTML.

Update

Brad Wilson

+2

, -

<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>

data-val="true" .

. , MVC, , .

:

 data-val-required="Message for requires"

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

. ( , jquery.unobtrisive.validate, )

+1

All Articles