开发者

Manually add validation to textbox without a model

开发者 https://www.devze.com 2023-02-17 23:48 出处:网络
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?

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.


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


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);
            }
        }
    }
}


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)

0

精彩评论

暂无评论...
验证码 换一张
取 消