HTML5 “required” attribute on asp:DropDownList

2019-09-08 12:36发布

Let's say I have this DDL on my page:

<asp:DropDownList ID="senha" runat="server" required="required" CssClass="form-control">
    <asp:ListItem Value="" Text="empty" Selected="True"></asp:ListItem>
    <asp:ListItem Value="1" Text="test1"></asp:ListItem>
    <asp:ListItem Value="2" Text="test2"></asp:ListItem>
</asp:DropDownList>

In this one, the required field will work without problem, if you don't select a value, then it will block the submit.
But what if the initial value is 0?

<asp:DropDownList ID="senha" runat="server" required="required" CssClass="form-control">
    <asp:ListItem Value="0" Text="empty" Selected="True"></asp:ListItem>
    <asp:ListItem Value="1" Text="test1"></asp:ListItem>
    <asp:ListItem Value="2" Text="test2"></asp:ListItem>
</asp:DropDownList>

Now the "required" attribute doesn't work anymore.
What I want to do is put a pattern in the value to only accept values greater than zero, but I'm not familiar with RegExp, and I don't know if the HTML "pattern" attribute will do what I want.
Can someone enlighten me?
I would rather use a solution that uses pure HTML, but if a minimal programming is required, then I don't have choice...

1条回答
一纸荒年 Trace。
2楼-- · 2019-09-08 13:12

If you just want to write mark up the RequiredFieldValidator should work

<asp:DropDownList ID="senha" runat="server" required="required" CssClass="form-control">
    <asp:ListItem Value="0" Text="empty" Selected="True"></asp:ListItem>
    <asp:ListItem Value="1" Text="test1"></asp:ListItem>
    <asp:ListItem Value="2" Text="test2"></asp:ListItem>
</asp:DropDownList>
<asp:RequiredFieldValidator ID="reqSenha" runat="server" SetFocusOnError="true"  InitialValue="0" ErrorMessage="*" ControlToValidate="senha" />
查看更多
登录 后发表回答