简体   繁体   中英

Html Custom Attribute creation and validation

I would like to create the validation for the controls dynamically. I have a page with more than 25 controls, those controls visibilities are based on the category and subcategories. For some of the categories the controls are required and some of them its not required. This is the business logic behind the scene.

So what I am planning here is, based on the categories and sub categories selection I am planning to include a html attribute isMandated=true for all the required fields. And on the onblur event going to validate its value. While clicking the button (while posting the page to server) I am planning to validate all the controls based on the isMandated attribute.

Is this approach is correct and all major browsers will support this kind of attribute addition?

If you want to include additional attributes you need to use the data- prefix. So in your case:

data-isMandated="true"

This is supported in all major browsers. To then grab the data using something like jQuery:

var isMandated = $(selector).attr("data-isMandated");

Your page maybe will not be valid with HTML validations, if your attribute is "isMandated" . The proper way is to create a custom attribute "data-isMandated" . This approach will works on all browsers (I created similar page before and it was work on IE7+, FF, Chrome). Maybe will be better, to add class to all required fields, instead of attribute isMandated=true and check all fields with this class. Also, you can use jquery validation - plugin . It include a couple of validations rules, like required fields, min/max values, phone number validation, email validation, etc.

If you work on asp.net you can use the RequiredFieldValidator on your different control such as the following example :

<tr>
<td>
<asp:RequiredFieldValidator runat=server
    ControlToValidate=txtName
    ErrorMessage="Identifier is required."> *
</asp:RequiredFieldValidator>
</td>
<td>User Identifier :</td>
<td><input type=text runat=server id=txtName></td>
</tr>

For the required fields you can use ValidationSummary property which display an " * " before required fields.

<asp:ValidationSummary runat=server
      headerText="there is error on this page/>

and don't forget the validation method :

public sub OnSubmit(source as Object, e as EventArgs)
    if Page.IsValid then
    ' Some code
    end if
end sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM