HTML5 Types in ASP.NET - asp.net

Site will exclusively be used on mobile devices. So for fields requiring only numeric input, I want to bring up the numeric keypad. I can successfully do this by using an html input element with the type set to tel. I want to add an asp:RequiredFieldValidator to this field and based on MSDN.
I need to set the input to runat="server". When I do this, I get this error;
tel is not a valid type for an input tag.
If I remove the runat="server", I get
Unable to find control id Contract referenced by the ControlToValidate property of ''
Here is my code:
<input type="tel" runat="server" id="Contract"></input>
<asp:RequiredFieldValidator runat="server" ControlToValidate="Contract"
ValidationGroup="IfOnRent" Text="*"
ErrorMessage="Contract Required">
</asp:RequiredFieldValidator>
Am I just out of luck and have to code my own validations?

You may want to leave "type" undeclared in your code "front". You can set this in the code behind (maybe in the Page_Init or Page_Load):
this.Contract.Attributes.Add("type", "tel");

If you have Microsoft .NET Framework 4 Reliability Update 1 (KB2533523) installed, than TextBox accepts new html5 input types (you would need it for UpdatePanel to recognize them on postback too).
Or you can just inherit HtmlInputText in your own control (any .net version - any input type):
[ToolboxData("<{0}:Input runat='server' />"), Themeable(true)]
public sealed class Input: HtmlInputText { }

If you are using C#
Contract.Attributes["type"]="tel"
Writing inline types for html inputs may produce parse error in .net. So add the above line of code in your PageLoad()

you can use
Make sure that the submit button has the same validationgroup property value as the requiredfieldvalidator

Related

Disable html required tag in vb.net

i need to disable the required tag of this textbox when a submit button is click
<asp:Textbox runat="server" id="username" required name="username" type="text" placeholder="myusername"/>
i tried to write the following code but it did not work
Dim tbUserName As TextBox =Page.FindControl("username")
tbUserName.required = False
can you please help me !
Since required is not part of the ASP.NET TextBox control's properties, thus there is no server-side property equivalent.
You can use the following to remove it:
username.Attributes.Remove("required")
Try this:
tbUserName.Enabled = False
Also, "Required" isn't a valid propert for the Textbox control. ref: http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.textbox.aspx
required is client-side attribute which does not have direct equivalent on server-side.
You can try
username.Attributes("required") = "false"
this works when you're already on the server. If you need to do this on client - handle form's onsubmit event and do something like
$get('username').setAttribute('required', 'false');
Of course the easiest way would be simple remove that attribute from textbox markup.

how to display only single message for multiple RequiredFieldValidators?

how to display only single message for multiple RequiredFieldValidator instead of individual message for RequiredFieldValidator ?
i want to as shown in following image..
my view is..
You will have to use ValidationSummary control for this. See this ValidationSummary Class MSDN article for details and example on how to do this. This article contains an example of what you are trying to figure out exactly.
set the HeaderText to something like "(*) Fields are required" to your validation summary.
you can leave error message field of each RequiredFieldValidator blank and put * in text field, then add ValidationSummary defining its header text with error msg this will works for your scenario.
<asp:RequiredFieldValidator ID="RequiredFieldValidator_overhead_name" runat="server" ControlToValidate="TextBox_overhead_name">*</asp:RequiredFieldValidator>
<asp:ValidationSummary ID="ValidationSummary_overhead_estimate" runat="server" DisplayMode="SingleParagraph" HeaderText="please insert data into fileds" />
This gentleman solved it here quite simply: http://www.cactusoft.com/blog_40
I can see what you are trying to do but it's difficult with the ASP.Net validators
The only way I can think to do it is remove the ValidationSummary altogether and manually create your own using the ASP.Net validator API and JQuery i.e.
Change all required validators to ErrorMessage = "*" Remove Text value
Remove Validation Summary
Add a label at the bottom to function as a custom validator summary. Style it red
In the page markup script something like
if(!Page_IsValid) {
$('#myCustomValidatorSummary').text('Please fill in required fields')
}
Page_IsValid is from the ASP.Net validator API. Set to false if the page fails validation.
Of course this assumes that you only have the required field validators on your form. If there is a mix then you will need to check if one or more of the required ones have failed by iterating through the Page_Validators on the client using JQuery/javascript
Honestly though I wouldn't do it - it's too hard
I would just do this - For each required field validator - set
Text="*"
ErrorMessage="[Field Name] is mandatory. Please supply a value." or similar.
Quick and easy way: add a CssClass to the ValidationSummary, then a css style that sets ul elements under that class to display: none.
For example:
<style>
.validationSummary ul {display:none}
<stlye>
...
<asp:ValidationSummary CssClass="validationSummary" ...
You should use the ValidationSummary Control from ASP.NET in addition to ValidationSummary you could also use the Group property to separate controls into logical groups. See http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.validationsummary.aspx for a bunch of examples.
use ValidationSummary
The ValidationSummary control is used to display a summary of all validation errors occurred in a Web page.
The error message displayed in this control is specified by the ErrorMessage property of each validation control. If the ErrorMessage property of the validation control is not set, no error message is displayed for that validation control.
http://asp-net-example.blogspot.in/2008/10/validationsummary-example-how-to-use.html
To add to Mike Godin's answer, for only showing a single alert message for multiple field validators:
Keep individual required messages. Add Validation Summary with DisplayMode="BulletList" and HeaderText="Please provide the required information above."
The "BulletList" display mode produces a unordered list of LI's inside the Validation Summary DIV, then hide UL via styling - only the "HeaderText" will show:
#validationSummary ul {
display:none;
}
<asp:ValidationSummary
id="validationSummary"
DisplayMode="BulletList"
EnableClientScript="true"
HeaderText="Please provide the required information above."
ValidationGroup="btnSubmit"
runat="server"/>

Why does AjaxControlToolkit TabContainer render all custom control markup properties?

This is a strange one to explain but hope I make sense.
Our organisation has a library of custom controls that we use in our solutions. One example of these controls is a textbox combined with a set of validators which can be configured appropriately by its properties set in the markup.
I now have a problem when using this control in (which I beleive to have narrowed it down) a TabContainer.
If I wanted to use the following markup in the container:
<scc:TextBox ID="txtEmailAddr" runat="server" CssClass="input EmailAddress" EnforceEntry="EmailAddress"
ErrorMessage_RequiredFieldNotCompleted="" ErrorMessage_ShowExclamation="true"
MaxLength="150" ShowErrorMessageBelow="false" Label="Email Address " />
When I save or reload the .aspx markup it then renders the following markup for the same control:
<scc:TextBox ID="txtEmailAddr" runat="server" CssClass="input EmailAddress" EnforceEntry="EmailAddress"
ErrorMessage_RequiredFieldNotCompleted="" ErrorMessage_ShowExclamation="True"
MaxLength="150" ShowErrorMessageBelow="False" Label="Email Address "
ClientSidePreventInvalidChars="True" EnableClientScript="True"
EnfoceOnPaste="False" EnforceMaxLengthWithRXOnMultiline="True"
EnforceOnPaste="False" EnforceSpaceInPostcode="True"
ErrorMessage_InvalidFormat="Email Address : Please enter a valid email address"
ErrorMessage_NumericValueInvalidOrOutOfRange="Email Address requires a number to be entered in the range to ."
GuidanceText="" GuidanceText_RenderInMouseoverPanel="False"
JavascriptURL="~/Include/TextBoxMaximumLength.js" LabelBold="False"
LabelCSSClass="" MaxValue="9999999" MinValue="-9999999" Read_Only="False"
RememberAnswer="False" RenderInParagraphs="True"
RenderRequiredTextForRequiredFields="True" Required="True"
RequiredField_InitialValue="" Rows="0" ShowMaxLength="False" Text=""
TextBox_TabIndex="0" TextboxSkinID="" TextMode="SingleLine"
TooltipPopup_BodyText="" TooltipPopup_TooltipText="(guidance)"
ValidationGroup="" ValidationExpression="" />
This would not be a problem other than the properties that are now being rendered in the markup are overriding default functionality of the actual control. In this case the default Email Address regular expression is being ignored because the property 'ValidationExpression' is being set to an empty string!
Again I could place the default regex in that property, but I would just like to understand why the markup is behaving in this manner?
Thanks.
Get the code for the AjaxContolToolkit and step through it to see why all properties are rendered. You can adjust that code as you need and compile the dll and use that. From personal experience, that is the only way I have found use for the Toolkit because of behaviors like you describe.

Page.Parsecontrol converts asp:textbox to textarea not input

I'm injecting some generated asp.net controls into a page using Page.ParseControl. I'm injecting the markup as follows:
Me.phScript.Controls.Add(Me.Page.ParseControl("<asp:TextBox runat=""server"" id=""txtAreaOfConcern"" TextMode=""multiline"" Rows=""5"" Width=""300"" MaxLength=""5"" />", True))
Now when this is rendered the source html comes out as
<textarea name="txtAreaOfConcern" rows="5" cols="20" id="txtAreaOfConcern" style="width:300px;">
Wheras a textbox added as per normal renders as follows:
<input name="_tbStaticInput" type="text" maxlength="20" id="_tbStaticInput" style="height:104px;width:263px;" />
The reason this is such a problem is that i no longer have the maxlength attribute which is needed for this page.
Is it possible to render an input through control injection, if so how?
You are setting the TextMode to multiline in the string you are passing to ParseControl, you will always get a textarea, that's how the TextBox control works. It will do the same thing if you put that in the markup on the page or instantiated a TextBox class and set the TextMode property to multiline.
Not related to your problem but it seems a strange way to create a control dynamically, the text you are parsing is a string literal and is not dynamic in any way. Why don't you just instantiate a TextBox class and set the properties, that way you get compile time checking that you are setting the properties to valid values. The way you are doing it your string could be changed to "AnIvalidValue" and everything would still compile fine but you would get a run time exception.

ASP.NET Custom Validator Error Message: Control referenced by the property cannot be validated

I use ASP.NET and have a Button and a CustomValidator, which has to validate
the button.
<asp:Button ID="saveButton" runat="server" OnClick="SaveButton_Click" Text="Speichern"
CausesValidation="true"/>
<asp:CustomValidator runat="server" ID="saveCValidator" Display="Static"
OnServerValidate="EditPriceCValidator_ServerValidate"
ControlToValidate="saveButton" ErrorMessage="">
When loading the page, I receive the error message:
"Control 'saveButton' referenced by
the ControlToValidate property of
'saveCValidator' cannot be validated."
What might be the problem? I searched on the net, but this didnĀ“t help much.
AFAIK, ControlToValidate property should point to input control or left blank for the CustomValidator control.
A reference from MSDN:
Use the ControlToValidate property to
specify the input control to validate.
This property must be set to the ID of
an input control for all validation
controls except the CustomValidator
control, which can be left blank. If
you do not specify a valid input
control, an exception will be thrown
when the page is rendered. The ID must
refer to a control within the same
container as the validation control.
It must be in the same page or user
control, or it must be in the same
template of a templated control.
The standard controls that can be
validated are:
System.Web.UI.WebControls.DropDownList
System.Web.UI.WebControls.FileUpload
System.Web.UI.WebControls.ListBox
System.Web.UI.WebControls.RadioButtonList
System.Web.UI.WebControls.TextBox
System.Web.UI.HtmlControls.HtmlInputFile
System.Web.UI.HtmlControls.HtmlInputPassword
System.Web.UI.HtmlControls.HtmlInputText
System.Web.UI.HtmlControls.HtmlSelect
System.Web.UI.HtmlControls.HtmlTextArea
You can only use a CustomValidator against Input controls that accept user input:
Client-side validation enhances the
validation process by checking user
input before it is sent to the server.
What you want to do is look here at Button Controls and Validation.

Resources