简体   繁体   中英

Custom Validator

So I have a custom validator that is working only partially. It basically has two things it's checking for: if two fields are filled out, and whether or not what has been entered in those fields already exists in the database. Checking against the database is working fine, but checking whether or not the fields are filled out is not. I don't want to use required field validators, since I want the error messages all in the exact same location on the page. I'm pretty sure I just messed up on something simple, but I just can't find it.

<strong>Course Prefix and Number:</strong>
<asp:TextBox ID="txtCoursePrefix" runat="server" Width="45" MaxLength="4" CssClass="caps"></asp:TextBox>
-
<asp:TextBox ID="txtCourseNum" runat="server" Width="45" MaxLength="6" CssClass="caps"></asp:TextBox>
<span class="required">*
<asp:CustomValidator ID="cvDuplicate" runat="server" ControlToValidate="txtCoursePrefix" ValidateEmptyText="true"></asp:CustomValidator>
</span>

Code behind:

'Check if fields have been filled out
    If txtCoursePrefix.Text Is Nothing Or txtCourseNum.Text Is Nothing Then
        cvDuplicate.ErrorMessage = "Required"
        args.IsValid = False
    End If
'Code that checks values against database goes here
'If matching record does not exist...
    If myValue IsNot Nothing Then
        cvDuplicate.ErrorMessage = "Course number is already taken."
        args.IsValid = False
    End If

So once again it is the first part that's not working, the second part is working fine.

It might be that the Text box is considered an empty string, not Nothing. Try this for your check:

If String.IsNullOrEmpty(txtCoursePrefix.Text) Or String.IsNullOrEmpty(txtCourseNum.Text) Then
    cvDuplicate.ErrorMessage = "Required"
    args.IsValid = False
End If

2 things needs to be checked

  1. Add following FieldRequired="True"
    <asp:CustomValidator ID="cvDuplicate" runat="server" ControlToValidate="txtCoursePrefix" ValidateEmptyText="true" FieldRequired="True"></asp:CustomValidator>

  2. On Server Side check if any place following is setup this.cvDuplicate.Enabled = false;

If you set following property as false. No validation will occur even if you set it up from Database on server side. So be careful when you set these up. If you do not set up these properties on .ASCX and set try to set them up from Database on server side (C# code) then they will work. this.cvDuplicate.Enabled = true;

ValidateEmptyText="False"
FieldRequired="False"

'Check if fields have been filled out
If String.IsNullOrEmpty(txtCoursePrefix.Text.Trim()) _
        OrElse String.IsNullOrEmpty(txtCourseNum.Text.Trim()) Then
    cvDuplicate.ErrorMessage = "Required"
    args.IsValid = False
End If

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