As the name implies, the RequiredFieldValidator is
used to make sure that the user enter a value for a specific field in the form.
A RequiredFieldValidator can be associated with a
control which cannot be empty while submitting the form.
The below code snipet adds a TextBox to an Asp.net
form and associates an Asp.Net RequiredFieldValidator to the text box to
make sure that the Name is entered before submitting the form.
<asp:TextBox
ID="txtName"
runat="server"
MaxLength="250">
</asp:TextBox>
<asp:RequiredFieldValidator
ID="valtxtName"
runat="server"
ControlToValidate="txtName"
Display="Dynamic"
ErrorMessage="Please enter Name."
SetFocusOnError="True">*
</asp:RequiredFieldValidator>
The RequiredFieldValidator also takes
care of the white spaces in the TextBox, the validator makes sure that
the user does not just type some white spaces and submit the form, it makes
sure that a valid Character or Number is entered before submitting the form.
Finally add a ValidationSummary
control to consolidate all the validations in the page.
<asp:Button ID="cmdSave"
runat="server"
Text="Save"
OnClick="cmdSave_Click" />
<asp:ValidationSummary
ID="valSummary"
runat="server"
DisplayMode="List"
ShowMessageBox="True"
ShowSummary="False"
</EnableClientScript="true" />
Once we are done with the code in
the .aspx page, we should also make sure that the validations are passed in ther server side in the
.vb/.cs code behind file.
Asp.Net performs the validations
both in the client and the server side, of the users' browser doesn’t support
JavaScript then the client side validation might get skipped, however the same
validation in done by Asp.Net in the server side also.
The Page.IsValid property returns true if the server side validations are succesful, else it will return false, hence we need to make sure that the Page.IsValid property is true before proceeding with the other operations.
The Page.IsValid property returns true if the server side validations are succesful, else it will return false, hence we need to make sure that the Page.IsValid property is true before proceeding with the other operations.
if (Page.IsValid)
{
//DB save and other server side logic goes
here
}
That’s it we have seen, how to use
the RequiredFieldValidator
to validate user input in an Asp.net form
No comments:
Post a Comment