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