How can I add a “Required” attribute to a dynamically-created (C#) element?

青春壹個敷衍的年華 提交于 2019-12-11 19:33:05

问题


I want to make some TextBoxes/text inputs "required" so that I can use the Validate jQuery validation plugin.

I tried this:

boxPayeeName = new TextBox
{
    CssClass = "finaff-webform-field-input",
    ID = "payeeName",
    Required = true
};

...but "Required" is not recognized there; so I tried this:

boxPayeeName = new TextBox
{
    CssClass = "finaff-webform-field-input",
    ID = "payeeName"
};
boxPayeeName.Attributes["required"] = "true";

I also tried this style of assigning to an attribute, on a similar control:

boxRequesterName.Attributes.Add("required", "true");

I've got validation via the Validate jQuery plugin set up like this in the jQuery (*.ascx) file:

$(window).load(function () {
    . . .
    this.validate();
});

...after having set it up like so:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.14.0/jquery.validate.min.js" type="text/javascript"></script>

...but no validation occurs when I exercise the page - I see no validation messages when I leave boxPayeeName and boxRequesterName blank. What am I missing?


回答1:


I had this same issue a week back and it was because the "required" attribute has issues in IE 7-9.

This is because, according to the post, all versions less than IE 10 are not entirely compliant with HTML 5.

If you are using .net, which I'm guessing you are since you're using C#, try using the RequiredFieldValidator feature.



来源:https://stackoverflow.com/questions/31708824/how-can-i-add-a-required-attribute-to-a-dynamically-created-c-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!