How to make inline errors read aloud by screen reader tools? - asp.net

I am doing accessibility testing. I created an email text box and added some validation as well. I want after typing wrong email as I move to next element screen reader should read the inline errors. I came across using aria-describeby and aria-live attribute but don't know how to use it in this code .
<asp:panel defaultbutton="btnEmail" cssclass="row" runat="server">
<biw:labelui associatedcontrolid="TextEmail" text="Email Address" runat="server" />
<biw:textbox id="TextEmail" width="200" runat="server" />
<asp:requiredfieldvalidator controltovalidate="TextEmail" text="*" errormessage="Please enter an e-mail address" display="dynamic" runat="server" />
<biw:emailaddressvalidator controltovalidate="TextEmail" text="*" errormessage="Please enter a valid e-mail address" display="dynamic" runat="server" />
<asp:customvalidator id="EmailValidator" controltovalidate="TextEmail" text="*" display="dynamic" runat="server" />
</asp:panel>

aria-describedby adds additional information to an element. An element usually has a name or label and additionally it can have a description. If your error message is in a separate element, such as a <div> or <span>, you can associate that <div> with the input field.
You code might look something like:
<label for="emailID">email address:</label>
<input id="emailID" aria-describedby="errorMsg">
<div id="errorMsg">invalid email address</div>
Some screen readers will read the aria-describedby after the field's label and others will tell you to hit a shortcut key to hear the description. It's up to the screen reader to decide how to present it to the user.
If the above field were in error, then it should have aria-invalid="true" as well.
<input id="emailID" aria-describedby="errorMsg" aria-invalid="true">
In order for the error message to be announced by screen readers, it should have aria-live="polite".
<div id="errorMsg" aria-live="polite"></div>
When you discover an error, you insert text into the <div> (via javascript) and the screen reader will announce it because it's a live region.
document.getElementById("errorMsg").innerHTML = "invalid email address";

Related

How to Authenticate Login form without using asp controls

I have put together a really nice Login page in which I am using HTML input tags for my username, password, and login button. I have two different login forms, one for each type of user (student user, and business user). I have never authenticated against a database so I assumed my method would be easy to execute. After scouring the web for easy methods to implement with what I already had I found it nearly impossible to figure out how to accomplish my goal without having to use asp:login control. Begrudgingly, I scrapped what I had and threw in the asp:login control. My problem is, that it was a pain to implement (creating stored procedures, and messing with the web.config), it looks hideous as it doesn't not conform with the CSS I had previously written, and the FormsAuthentication I am using only allows me to redirect one user after login (to the home portal upon succesful login, and back to the login page if login failed.) using the authentication Forms mode in my Web.config:
<forms defaultUrl="~/InteriorStudentPortal.aspx" loginUrl="~/ExteriorLogin.aspx" slidingExpiration="true" timeout="2880"></forms>
Since I have two users I need to redirect based on what user is logging in. Here is a sample of the asp:login control that I have been using:
<asp:Login ID="Login1" runat="server" CssClass="Login" OnAuthenticate= "ValidateStudent" Width="313px"></asp:Login>
Along with the back code:
Imports System.Data
Imports System.Configuration
Imports System.Data.SqlClient
Imports System.Web.Security
Partial Class ExteriorLogin
Inherits System.Web.UI.Page
Protected Sub ValidateStudent(sender As Object, e As AuthenticateEventArgs) Handles Login1.Authenticate
Dim studentId As Integer = 0
Dim constr As String = ConfigurationManager.ConnectionStrings("DatabaseConnectionString").ConnectionString
Using con As New SqlConnection(constr)
Using cmd As New SqlCommand("Validate_Student")
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.AddWithValue("#Username", Login1.UserName)
cmd.Parameters.AddWithValue("#Password", Login1.Password)
cmd.Connection = con
con.Open()
studentId = Convert.ToInt32(cmd.ExecuteScalar())
con.Close()
End Using
Select Case studentId
Case -1
Login1.FailureText = "Username and/or password is incorrect."
Exit Select
Case -2
Login1.FailureText = "Account has not been activated."
Exit Select
Case Else
FormsAuthentication.RedirectFromLoginPage(Login1.UserName, Login1.RememberMeSet)
Exit Select
End Select
End Using
End Sub
End Class
My goal is to either continue using the asp:login controls and figure out how to allow for multiple user redirects after login....OR preferably, authenticate without using the asp:login and use my original HTML and CSS. Here is what I had prior to using the asp control:
<%-- STUDENT LOGIN --%>
<div class="student_login">
<div id="wrapper">
<form name="login-form" class="login-form" action="" method="post">
<div class="header">
<h1>Student Login</h1>
<span>Sign in below to login to start showing your skills, earning money, and gaining valuable experience...and did I mention earning MONEY.</span>
</div>
<div class="content">
<input name="username" type="text" class="input username" placeholder="Username" />
<input name="password" type="password" class="input password" placeholder="Password" />
</div>
<div class="footer">
<input type="submit" name="submit" value="Login" class="button" />
Register
</div>
</form>
</div>
</div><!--close student_login-->
NOTE: This section of code is written within a content placeholder. The master page does have a <form runat="server"></form> tag encompassing the body of the page. I do not have any back code for this particular method as I really have no clue how to authenticate without using the asp:login control and FormsAuthentication. Can someone please help me understand how to accomplish authenticating without the asp:login so that I can keep my nicely designed Login form? And please be generous or kind with the comments/explanation, this is my first login form so I have no experience doing this.
You can use the LayoutTemplate of the Login control to do what you want.
The trick is that you need to use a Literal with the ID of FailureText, the user field is a TextBox with ID of UserName, and another TextBox with the ID of Password.
You also will need to trigger a Login command which could be a Button.
This allows you to customize your own layout, I've done this a few times myself. Below is a quick copy/paste untested version with your HTML as an example.
See an MSDN reference at https://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.login.layouttemplate.aspx
<asp:Login ID="Login1" runat="server"
OnAuthenticate="ValidateStudent"
Width="100%">
<LayoutTemplate>
<div class="student_login">
<div id="wrapper">
<asp:Literal ID="FailureText" runat="server"></asp:Literal>
<asp:ValidationSummary ID="vsLogin" runat="server" ValidationGroup="Login" />
<div class="header">
<h1>Student Login</h1>
<span>Sign in below to login to start showing your skills, earning money, and gaining valuable experience...and did I mention earning MONEY.</span>
</div>
<div class="content">
<asp:TextBox id="UserName" runat="server" CssClass="input username" placeholder="Enter your username"></asp:TextBox>
<asp:RequiredFieldValidator id="rfvUserName" runat="server"
ControlToValidate="UserName"
Display="None"
ErrorMessage="Username is required"
ValidationGroup="Login">
</asp:RequiredFieldValidator>
<asp:TextBox id="Password" runat="server" CssClass="input password" TextMode="Password" placeholder="Password"></asp:TextBox>
<asp:RequiredFieldValidator id="rfvPassword" runat="server"
ControlToValidate="Password"
Display="None"
ErrorMessage="Password is required"
ValidationGroup="Login">
</asp:RequiredFieldValidator>
</div>
<div class="footer">
<asp:Button ID="Login" runat="server" CommandName="Login" CssClass="button" Text="Login" ValidationGroup="Login" />
Register
</div>
</div>
</div>
</LayoutTemplate>
</asp:Login>

Required field validator is not working

I have used a required field validator, on click of add Button error message will be displayed but whatever code written on onclick event will be executed even if the field is empty.
<div class="form-group posrel">
<asp:Label ID="Label1" runat="server" AssociatedControlID="txtDept"><i class="fa fa-pencil"></i></asp:Label>
<asp:TextBox runat="server" ID="txtDept" placeholder="Department Name" ValidationGroup="ss1"></asp:TextBox>
<div class="text-right validators">
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
ErrorMessage="Department Name" ControlToValidate="txtDept" ValidationGroup="ss1">
</asp:RequiredFieldValidator>
</div>
</div>
Below is the code snippet of add button -
<div class="form-group pull-right">
<asp:LinkButton runat="server" ID="lnkbtnaddept" CssClass="btn btn-primary" ValidationGroup="ss1" OnClick="lnkbtnaddept_Click">
<asp:Label runat="server" Text="Add" ID="lbladddept"></asp:Label>
<i style="margin-left: 10px;" class="fa fa-send"></i>
</asp:LinkButton>
</div>
May be this will help you out:
On link-button click event validate your page.
Page.Validate("validation group");
if(Page.isValid){
// your code logic
}
for more on page validate follow the link
https://msdn.microsoft.com/en-us/library/0ke7bxeh%28v=vs.110%29.aspx
Turn on JS support for the Validator control by adding attribute:
EnableClientScript="True"
It should prevent a post-back until text box is filled.
take your Id of RequiredFieldValidator and update on back end
or .cs page.
Ans RequiredCityName.Update();

How to set Focus on Textbox while TextChaged Event in Fired - Asp .Net

I have a form with 2 Text Boxes (along with other controls). Both of them have TextChanged Event. I'm using Tab Key to go from one Control to another.
After entering some value in the first TextBox and then pressing Tab, the focus is not going to Second TextBox.
I'm using TextBox2.Focus();
But this is not working.
Your Code is not useful for me. My TextBox does have OnTextChanged Event. I implemented TabIndex, but this is not working after PostBack.
Why to do server side code when you can handle it with plain html property tabindex
Plain Html Code
<span>2</span><input type='text' tabindex="1" /><br/>
<span>1</span><input type='text' tabindex="3" /><br/>
<span>3</span><input type='text' tabindex="4" /><br/>
<span>4</span><input type='text' tabindex="2" /><br/>​
ASP.NET Code
<asp:TextBox ID="txtField1" runat="server" tabindex="1" />
<asp:TextBox ID="txtField2" runat="server" tabindex="2" />
For working demo see here

ASP.NET CustomValidator control interferes with jQuery validation on form submission

I have a simple form that uses jQuery validation to notify the user of input errors, etc. When I add an ASP.NET CustomValidator to the form, it causes the page to postback and skip the jQuery validation. I need the form to not be submitted to the server until the client-validation is correct. Has anyone seen this before?
This is my form:
<form id="form1" runat="server">
<core:standardscriptmanager runat="server" />
<div>
<asp:textbox id="Email" name="Email" runat="server" cssclass="_RegisterFormValidate FormField Email {required:true, email:true, messages:{required:'You must enter an email address.', email:'Please enter a valid email address.'}}" maxlength="200" columns="75" width="98%" tooltip="Your email address"></asp:textbox>
<br /><br />
<core:recaptcha runat="server" />
<br />
<asp:linkbutton id="CreateAccount" runat="server" onclick="CreateAccount_Click" text="create"></asp:linkbutton>
</div>
</form>
And this is the core:recaptcha control that contains the custom validator:
<script type="text/javascript"
src="http://www.google.com/recaptcha/api/challenge?k=XXXKEY">
</script>
<noscript>
<iframe src="http://www.google.com/recaptcha/api/noscript?k=XXXKEY"
height="300" width="500" frameborder="0"></iframe><br>
<textarea name="recaptcha_challenge_field" rows="3" cols="40">
</textarea>
<input type="hidden" name="recaptcha_response_field"
value="manual_challenge">
</noscript>
<asp:customvalidator id="RecaptchaValidator" runat="server" controltovalidate="DummyInput" onservervalidate="ServerValidate" validateemptytext="true" />
<asp:textbox id="DummyInput" runat="server" cssclass="Hidden"></asp:textbox>
Note: The DummyInput is only there to make the CustomValidator happy, my ServerValidate event correctly deals with the captcha results.
The ServerValidate portion of the CustomValidator is working fine during the postback, but I need it to stop interfering with the client-side validation. If I remove the CustomValidator from the recaptcha control, everything plays nice.
Do I need to do something like call jquery-validate in the CustomValidator's clientvalidationfunction in order to make this work correctly?
Any thoughts or suggestions would be welcome.
So it turns out the answer to this issue was to set CausesValidation="False" on my linkbutton and then call Page.Validate() in the linkbutton's OnClick handler.
It's not exactly the solution I was looking for since I'll have to remember to do those things every time I want to use recaptcha (or any custom validator for that matter) but this seems to work for now.
You can set the EnableClientScript property of your validator to false:
<asp:CustomValidator id="RecaptchaValidator" runat="server"
ControlToValidate="DummyInput" OnServerValidate="ServerValidate"
ValidateEmptyText="True" EnableClientScript="False" />

Apostrophes in XML and Databound Controls

In my XML, it's possible for an apostrophe to appear in a node's value:
<Root>
<Sections>
<SectionA>
<Heading>Title</Heading>
<Description>This is section 'A'</Description>
</SectionA>
</Sections>
</Root>
If I have controls bound to this XML:
<asp:FormView ID="myFormView" runat="server" DataSourceID="myXmlDataSource">
<ItemTemplate>
<div>
HTML Element:
<input type="text" value='<%# XPath("text()") %>' />
</div>
<div>
Server Control:
<asp:TextBox id="myTextBox" runat="server" value='<%# XPath("text()") %>' />
</div>
</ItemTemplate>
</asp:FormView>
<asp:XmlDataSource ID="myXmlDataSource" runat="server" XPath="Root/Sections/SectionA" />
I've noticed that the text is correctly displayed in the asp:TextBox but not in the INPUT element. I'm assuming that it's because server controls correctly escape the apostrophe. To work around this, I tried changing the Description node in the XML to the following:
<Description>This is section 'A'</Description>
Again, this displayed correctly in the asp:TextBox, but not in the INPUT element.
My next attempt was to wrap the node's value in a CDATA:
<Description><![CDATA[This is section 'A']]></Description>
Finally it was displaying correctly in the INPUT element, but now the asp:TextBox displayed the two "& # 3 9 ;". I've even tried "& a p o s ;" but the result is the same.
What is the best approach for the use of apostrophes in XML where the value can be displayed in either a server control or HTML element?
Here you have single quotes surrounding the value argument for the html element:
<input type="text" value='<%# XPath("text()") %>' />
This renders:
value='This is section 'A''
Instead use double quotes:
<input type="text" value="<%# XPath("text()") %>" />
Which renders:
<input type="text" value="This is section 'A'" />
Use &apos; instead. It is one of the 5 permitted entities in XML.
So your code would look like:
<Description>This is section &apos;A&apos;</Description>

Resources