I have search the net and not found anything that has helped, so thought I would ask on here.
I have a simple asp.net 2.0 form.
<form runat="server">
<asp:ValidationSummary ID="ValidationSummary1" runat="server" />
<asp:TextBox ID="txt1" runat="server" ValidationGroup="valGroup1"></asp:TextBox>
<asp:RequiredFieldValidator ControlToValidate="txt1" ValidationGroup="valGroup1" runat="server" Display="Dynamic" ID="val1" ErrorMessage="*"></asp:RequiredFieldValidator>
<asp:Button ID="btn1" runat="server" ValidationGroup="valGroup1" CausesValidation="true" Text="submit" />
</form>
What I want to do is to change the styling on the input when validation fails for that particular input. Preferably by adding a class, not inline styles.
I can do this when javascript is not available via code behind, but what I want to do is have the same happen when javascript is available.
I know that ASP.NET injects a global js variable called Page_Validators, which is an array of all of the validator spans on the page. Is there an easier way to do this other than looping through all of these??
EDIT
I can sort of do it with the following:
<script type="text/javascript">
function ValidateInputs() {
var validators = Page_Validators;
for (var i = 0; i < validators.length; i++) {
var validator = validators[i];
if (!validator.isvalid) {
document.getElementById(validator.controltovalidate).setAttribute("style", "border:solid 1px red;");
}
}
}
</script>
Was just wondering if there was a better way??
And can I get the microwoft validation scripts to call my validation method? or can I hook into the validation event manually?
That's a pretty good way of doing it; there is no public event or something else to tap into, unless you want to start replacing public events with your own custom ones (that gets messy).
HTH.
It turns out my answer is the only one that I am going to get!
<script type="text/javascript">
function ValidateInputs() {
Page_ClientValidate();//Validate the validators using microsofts validation
var validators = Page_Validators;
for (var i = 0; i < validators.length; i++) {
var validator = validators[i];
if (!validator.isvalid) {
document.getElementById(validator.controltovalidate).setAttribute("style", "border:solid 1px red;");
}
}
}
</script>
Also, on the button, set the OnClientClick="ValidateInputs();" to OnClientClick="ValidateInputs();return false;"
Related
there are 3 validators on an textbox,
asp:RegularExpressionValidator
asp:RangeValidator
asp:CompareValidator
some input will trigger all 3 of them, how can I stop firing the rest upon any error?
May be this can help you.. you can intercept ValidatorValidate method of ASP.Net validation framework and selectively disabled the validator controls you want based on any given validation control result.
<asp:TextBox ID="tbText" runat="server"></asp:TextBox>
<asp:RegularExpressionValidator EnableClientScript="true" ValidationExpression="\d" ID="rang" runat="server" ControlToValidate="tbText" >sdfsdfsdfsdfsdfsd</asp:RegularExpressionValidator>
<asp:RangeValidator EnableClientScript="true" Type="Date" MinimumValue="10/10/2000" MaximumValue="10/10/2013" runat="server" ID="rang2" ControlToValidate="tbText" >23444444444444</asp:RangeValidator>
<asp:Button ID="btn" runat="server" Text="submit"/>
<script language="javascript">
var oldValidatorValidate = ValidatorValidate;
function MyValidatorValidate(val, validationGroup, event) {
//first call the original one
oldValidatorValidate(val, validationGroup, event);
//Here you can check val.isvalid - e.g write your logic here, like check for the correct validator etc etc
//alert(val.id + ":" + val.isvalid);
if (!val.isvalid) {
var myVal = document.getElementById('<%=rang2.ClientID %>');
//ValidatorEnable(myVal, false);
}
}
ValidatorValidate = MyValidatorValidate;
</script>
I have an asp.net web for with a few Validation controls on:
<div class="form-row">
<label>Email</label>
<asp:TextBox ID="txtUserName1" runat="server" onchange="validate(this)"> </asp:TextBox>
<asp:RequiredFieldValidator ID="reqUserName1" runat="server" ControlToValidate="txtUserName1"
ErrorMessage="- The email address field is required" Text="*" CssClass="error_star" Width="10px" ValidationGroup="Register"></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="RegularExpressionValidator2" CssClass="error_star" runat="server" ErrorMessage="- Invalid Email Address" Text="*"
ValidationExpression="\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*" ControlToValidate="txtUserName1"
ValidationGroup="Register"></asp:RegularExpressionValidator>
</div>
I have a button to submit the form
<asp:Button ID="cmdSubmit" runat="server" Text="Create Account" CssClass="small-button"
ValidationGroup="Register" CausesValidation="true" OnClientClick="validateForm()" OnClick="cmdSubmit_Click" />
The first time I hit the button some client side validation is run and my validateForm() method is not hit. for subsequent times I click the submit button my custom validation works fine.
How do I attach some custom JavaScript to the client side validation?
here' the javascript
function validateForm() {
$("input[type=text], input[type=password]", "#registerForm").each(function () {
validate(this)
});
}
function validate(control) {
// Change the colour of the border
for (var i = 0; i < control.Validators.length; i++) {
if (!control.Validators[i].isvalid) {
control.style.border = "1px solid red"
return;
}
}
control.style.border = "1px solid #E1D7CE"
}
The page wasn't validating, so the javascript was working but it thought all the controls where valid, I added this
if (!Page_ClientValidate("Register")) {
Page_ClientValidate("Register")
}
to validate the page.
You can use a custom validator
http://asp.net-tutorials.com/validation/custom-validator/
they work just like any other asp.net validators, accept you get to write the function that handles the validation and sets IsValid flag. This will in turn allow/prevent postback to occur.
1- use CustomValidator, hence all you validation logic will reside in your JavaScript Code, lets say you want to validate TextBox for number > 12, javascript code would be like:
function Validate(src, eventargs)
{
var control = Document.GetElementByID(src);
if(control.value > 12)
eventargs.IsValid = true;
else
eventargs.IsValid = false;
}
2- Use CustomValidator's ClientValidationFunctionProperty set to ="Validate" (the JavaScript Function)
when you try to do any postback, then the Page.Validators collection is evaluated and so your CustomValidator
I am trying to use the following script in asp.net:
<script language="javascript" type="text/javascript">
function checktext() {
var txt = document.getElementById('tbComments');
if (txt.Text.Length > 0) {
alert('Thank you for submitting feedback.');
return true;
}
else {
alert('Sorry, you must enter text before submitting.')
return false;
}
}
</script>
<asp:Button ID="btnSave" runat="server" Text="Submit" onclick="btnSave_Click" OnClientClick="checktext();" />
I have tried using it on the onclick event.. the script will just not work at all.
Any Ideas?
you can use the ClientID property for getting the name of a Control on the client side. I suggest you to try jQuery for all these though
var txt = document.getElementById('<%=tbComments.ClientID%>');
besides, the OnClientClick has to receive a true or false value, in order to "know" whether to send the request to the server; so you have to change it with something like OnClientClick="return checktext();"
Try calling it like this:
<asp:Button
ID="btnSave"
runat="server"
Text="Submit"
onclick="btnSave_Click"
OnClientClick="return checktext();" />
Also this line looks suspicious in a web forms application:
document.getElementById('tbComments');
Make sure that the generated id of your control is not prefixed with something else.
Replace:
<asp:Button ID="btnSave" runat="server" Text="Submit" onclick="btnSave_Click" OnClientClick="checktext();" />
with:
<asp:Button ID="btnSave" runat="server" Text="Submit" onclick="btnSave_Click" OnClientClick="return checktext();" />
Replace:
var txt = document.getElementById('tbComments');
With:
var txt = document.getElementById('<%= tbComments.ClientId %>');
HTH.
everone else mentioned OnClientClick so I won't address that.
assuming tbComments is a textbox of some kind, this line
if (txt.Text.Length > 0) {
is going to fail because Text is not a property of html inputs or textareas, which is how asp.net textboxes are rendered. what you want is
if (txt.value.length > 0) {
also, is there some reason you're not using a regular asp.net RequiredFieldValidator control? you're doing more work than you need to. If you absolutely have to have alert boxes, you can use a CustomValidator control to call your function (you'll have to tweak it to fit the model).
I have an label "test" comimg from .cs [c# code] text="data saved successfully" . but once I click the save button i need to clear its text
right now I have 3 required field validators. with message [cannot be blank, cannot be blank,cannot be blank,] as user as clicked the save button I need to clear the text of the label. But need to show the required fields validator message
any idea how to solve it
thank you
make a javascript function like:
<Script type="text/javascript">
function clearText(cntId) {
var cnt = document.getElementById(cntId);
cnt.value ="";
return false;
}
</script>
then on your submit button attach a client side event
<asp:Button id='btnSubmit' Text='Submit' onClientClick='clearText("<%this.lblLable.ClientId%>");' .... />
On the client-side use a script like this
<script type="text/javascript">
function clearLabelValue(){
var labelObj = document.getElementById("<%= myLabel.ClientID %>");
labelObj.value = "";
}
</script>
<asp:Label id="myLabel" runat="server" Text="Some text"/>
<asp:Button id="myButton" runat="server" Text="Submit" OnClientClick="clearLabelValue();return false;"/>
Didn't test it in detail, but should work.
It is not really clear what you want to achieve, although I have the feeling there may be a "better" (more standard compliant) way of achieving what you want. Maybe you could describe more clearly what you want, so we may be able to help you.
In these situations when a particular button has validation attached to it and also we need to fire some javascript what is done is to define a javascript function which is called on click of save button.
What this javascript function does:
This function will take your label and will set its value as blank so that the text is cleared.
Now in order to validate the page which happens internally (in case the javascript function is not written on the save button click) we need to explicitly call what asp.net call for client side validation.
There is a function page_ClientValidate which needs to be called from this javascript function so that validation is still done and we also do some other processing like clearing the label in this case.
<!--for cleaning to label ; -->
document.getElementById("MyLabel").innerHTML = "";
<!--and label is like;-->
<asp:Label ID="MyLabel" runat="server" ></asp:Label>
You can simply achieve this using below script:
<script type="text/javascript">
function clearLabelValue(){
document.getElementById("<%= myLabel.ClientID %>").innerText=""
}
</script>
<asp:Label ID="myLabel" runat="server" ></asp:Label>
<asp:Button id="myButton" runat="server" Text="Submit" OnClientClick="clearLabelValue();"/>
I'm working with ASP.NET 3.5.
I have a list box that users must add items to (I've written the code for this). My requirement is that at least one item must be added to the listbox or they cannot submit the form. I have several other validators on the page and they all write to a ValidationSummary control. I would like this listbox validation to write to the Validation Summary control as well. Any help is greatly appreciated. Thank you.
Drop in a custom validator, Add your desired error message to it, double click on the custom validator to get to the code behind for the event handler, and then you would implement server side like this:
protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
{
args.IsValid = ListBox1.Items.Count > 0;
}
Also you can implement client side javascript as well.
I just threw this up on a page and tested it quickly, so you might need to tweak it a bit: (The button1 only adds an item to the List Box)
<script language="JavaScript">
<!--
function ListBoxValid(sender, args)
{
args.IsValid = sender.options.length > 0;
}
// -->
</script>
<asp:ListBox ID="ListBox1" runat="server"></asp:ListBox>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" ValidationGroup="NOVALID" />
<asp:Button ID="Button2" runat="server" Text="ButtonsUBMIT" />
<asp:CustomValidator ID="CustomValidator1" runat="server"
ErrorMessage="CustomValidator"
onservervalidate="CustomValidator1_ServerValidate" ClientValidationFunction="ListBoxValid"></asp:CustomValidator>
If you add a validation summary to the page, you error text should show up in that summary if there is no items in the ListBox, or other collection-able control, what ever you want to use, as long as the ValidationGroup is the same.
This didn't work for me:
function ListBoxValid(sender, args)
{
args.IsValid = sender.options.length > 0;
}
But this did:
function ListBoxValid(sender, args)
{
var ctlDropDown = document.getElementById(sender.controltovalidate);
args.IsValid = ctlDropDown.options.length > 0;
}
gotta make sure to add these properties to the CustomValidator:
Display="Dynamic" ValidateEmptyText="True"
<asp:CustomValidator
runat="server"
ControlToValidate="listbox1"
ErrorMessage="Add some items yo!"
ClientValidationFunction="checkListBox"
/>
<script type="Text/JavaScript">
function checkListBox(sender, args)
{
args.IsValid = sender.options.length > 0;
}
</script>
Actually this is the proper way to make this work (as far as the JavaScript is concerned).
ListBox.options.length will always be your total number of options, not the number you have selected. The only way I have found that works is to use a for loop to go through the list.
function ListBoxValid(sender, args)
{
var listBox = document.getElementById(sender.controltovalidate);
var listBoxCnt = 0;
for (var x =0; x<listBox.options.length; x++)
{
if (listBox.options[x].selected) listBoxCnt++;
}
args.IsValid = (listBoxCnt>0)
}
this work for me
<script language="JavaScript">
function CheckListBox(sender, args)
{
args.IsValid = document.getElementById("<%=ListBox1.ClientID%>").options.length > 0;
}
</script>
<asp:ListBox ID="ListBox1" runat="server"></asp:ListBox>
<asp:CustomValidator ID="CustomValidator1" runat="server"
ErrorMessage="*Required" ClientValidationFunction="CheckListBox"></asp:CustomValidator>
You will want to register your control with the page by sending in the ClientID. Then, you can use Microsoft AJAX to grab your control and check the values.