I decided to do some javascript validation like I would have done with classic ASP instead and use an alert message box rather than displaying items on the page. Turns out it was pretty easy, first change the button(or other control) to use its OnClientClick method to call a javascript function like so:
<asp:Button ID="btnPerformTask" runat="server" Text="Perform Task" OnClick="btnPerformTask_Click" OnClientClick="return validateMe();" />
Then create the javascript function to perform the validation (here I have done it against a textbox with an id of txtInputToCheck):
function validateMe() {
if (document.getElementById('<%=txtInputToCheck.ClientID%>').value.length == 0) {
alert("Text has not been entered.");
return false;
}
return true;
}I needed to use the txtInputToCheck.ClientID as the ID that appears on the page when rendered is not the same as you define in the HTML of your page. Then I simply check the value length to see if its been entered and return false if so.
Returning false stops the page from posting and returning true allows it to do so, return true is put at the end so if all validation is ok I am letting the page continue.
No comments:
Post a Comment