Custom Validator - Error message does not display on front end - javascript

I am trying to use a CustomValidator to validate entering of a string - po box
Basically, I want the users to avoid typing their postal address in address box for which I have written a function with the regular expression. But the problem is that the error message does not appear though it triggers the function. (I know this because I checked this by placing breakpoints in my Javascript function using Chome developer tools.)
Below is my .ascx file code.
<div class="clearfix">
<asp:Label ID="lblAddress" runat="server" Text="Address" AssociatedControlID="txtAddress"
class="formlabel firstfocus"></asp:Label>
<div class="input">
<asp:TextBox ID="txtAddress" runat="server" CssClass="large" MaxLength="80"></asp:TextBox>
<asp:RequiredFieldValidator ID="valAddress" runat="server" ControlToValidate="txtAddress"
CssClass="error-block" Display="Dynamic" ErrorMessage="<p>Address is required</p>"
SetFocusOnError="True"></asp:RequiredFieldValidator>
<asp:CustomValidator ID="valAddressPOBOX" runat="server" EnableClientScript="true" ValidateEmptyText="true" ErrorMessage="<p>Cannot contain a PO Box number</p>" ClientValidationFunction="AddressPOBoxValidation" ControlToValidate="txtAddress" Display="Dynamic" SetFocusOnError="True"></asp:CustomValidator>
</div>
</div>
The RequiredFieldValidator triggers the error message.
Below is the screenshot showing error message triggered from RequiredFieldValidator
With CustomValidator the trigger happens but the error message does not come up. I have checked on other CustomValidators on the same ascx page and made sure this one has properties no different from them, but still, if I am missing on any visibility property, feel free to correct me.
Below are 2 screenshots to show how the effect of CustomValidator takes place.
Before entering po box
After entering po box (Notice how the gap between address and address 2 increases.)
Coming on to the Javascript side, below is the function
function CheckPOBOXAddress(address) {
var poboxPattern = /(p\.?\s?o?\.?\s?b\.?(ox)\.?(\s|[0-9])?|post\soffice)/i;
if (poboxPattern.test(address))
return true;
else
return false;
}
function AddressPOBoxValidation(sender, args) {
var address = args.Value;
if (CheckPOBOXAddress(address)) {
args.IsValid = false;
return;
}
args.IsValid = false;
}

I have found a solution to my problem.After days of trial, error and research this worked for me:
<asp:CustomValidator ID="CustomAddressValidator" runat="server" ClientValidationFunction="CheckAddressValidation" ControlToValidate="txtAddress" CssClass="error-block" Display="Dynamic" SetFocusOnError="True">Cannot contain a PO Box number</asp:CustomValidator>
Also I modified my Javascript into a single function :
function CheckAddressValidation(sender, args) {
var address = args.Value;
var addressPattern = /(p\.?\s?o?\.?\s?b\.?(ox)\.?(\s|[0-9])?|post\soffice)/i;
if (addressPattern.test(address)) {
args.IsValid = false;
return;
}
args.IsValid = true;
}
Lesson - The other part of the CreateProfile.ascx file has Custom Validator in the same format as I posted originally. My superiors feel that Microsoft has done some changes to this probably that is why putting an error message in ErrorMessage tag does not seem to work. Feel free to correct me if I am wrong somewhere. But if you're someone who is stuck in a similar situation, my solution should help.

Related

Search keywords with enter key - BUG

So, i'm developing a search feature in my website, and i want to redirect the user to a page with the keywords he is trying to search.
The following code works, but there is a bug: when i click enter in my homepage it works. The user is successfully redirected to my search page with the results. But when i'm in that page (or any other page) the enter key does not work! Only the button works all the time! It's a strange error and i dont know what to do...
This code is in my masterpage (.net 4.0) and it is the parent of all my webforms (including home). Can anyone help me?
<asp:TextBox ID="TBPesquisa" runat="server" placeholder="Pesquise produtos aqui" onkeypress="return runScript(event)"></asp:TextBox>
<button id="BTPesquisa" class="button-search" type="button" onClick="javascript:window.location.assign('/Pesquisa?val='+encodeURIComponent(document.getElementById('TBPesquisa').value));">Pesquisar</button>
<script>
function runScript(e) {
if (e.keyCode == 13) {
$("#BTPesquisa").click();
}
}
</script>
Probably, the reason is that the TBPesquia field wasn't found, as this is an asp.net textbox control, and the ID might not be what you expect it to be.
Now you could either go for setting the ClientID property, like:
<asp:TextBox ID="TBPesquisa" ClientID="TBPesquisa" runat="server" placeholder="Pesquise produtos aqui" onkeypress="return runScript(event)"></asp:TextBox>
or you could rewrite your handler slightly, by doing the following
<asp:TextBox ID="TBPesquisa" runat="server" placeholder="Pesquise produtos aqui" onkeypress="runScript(event)"></asp:TextBox>
and change the runscript to:
function runScript(e) {
var source = e.target;
if (e.keyCode === 13) {
searchFor( source.value );
e.preventDefault();
}
}
function searchFor( textValue ) {
window.location.assign('/Pesquisa?val=' + encodeURIComponent(textValue));
}
I would btw rather put the code for searching outside of the searchbutton itself, it only makes sense to have this outside of your html element

Trigger jQuery function / event from c# code-behind

I hope I will be able to explain my problem clearly.
Scenario:
Asp.net web page with UpdatePanel. Some properties of controls are changeable via UI trigger and are set in jQuery (for faster response, as this page is expected to accept input data of at least 500 records per day).
Example below, (if written in c# code, the logic is like this: txtIDNumber.Enabled = chkIsReceiptRequired.Checked; rfvIDNumber.Enabled = chkIsReceiptRequired.Checked;):
Markup:
<asp:CheckBox ID="chkReceiptRequired" runat="server" Text="Receipt required" />
<asp:TextBox runat="server" ID="txtIDNumber" Width="150px" style="float: left;" />
<asp:RequiredFieldValidator ID="rfvIDNumber" runat="server" ForeColor="Red"
ErrorMessage="Enter ID No." ControlToValidate="txtIDNumber" ValidationGroup="save" />
Snippet of default jQuery code (upon page load, chkReceiptRequired is unchecked, validator and textbox will only be enabled upon ticking chkReceiptRequired):
<script type="text/javascript">
function pageLoad(){
$('input[id$=_txtIDNumber]').prop('disabled', true);
ValidatorEnable($("[id$='rfvIDNumber']")[0], false);
$('input[id$=_chkReceiptRequired]').change(function () {
$('input[id$=_txtIDNumber]').prop('disabled', !$(this).is(':checked'));
$('input[id$=_txtIDNumber]').val(!$(this).is(':checked') ? '' : $('input[id$=_txtIDNumber]').val());
ValidatorEnable($("[id$='rfvIDNumber']")[0], $(this).is(':checked'));
});
}
</script>
I'm using this same page to load the data here to perform record update. Code snippet of data loading:
var maintableComponent = new MainTableComponent();
var maintableData = maintableComponent.GetMainTableDataById(rowId);
chkReceiptRequired.Checked = maintableData.IsReceiptRequired.Value;
txtIDNumber.Text = maintableData.IDNumber;
//todo: enable txtIDNumber and rfvIDNumber from here
The problem: by right, upon page render for update, because chkReceiptRequired is checked, supposedly txtIDNumber should be enabled. But my problem is, it is not. What can I do to enable the txtIDNumber and rfvIDNumber upon data loading from code-behind?
*I have already tried this link and this but it doesn't seem to work.
Please, please help me. The snippets I posted here are just one of many jQuery validations that I desperately need to address. Thanks in advance.
Feeling incredibly stupid right now. Figured out how to fix it after sleeping it off. :P
I just changed the default jQuery code to this:
var isReceiptRequired = $('input[id$=_chkReceiptRequired]').is(':checked');
$('input[id$=_txtIDNumber]').prop('disabled', !isReceiptRequired);
ValidatorEnable($("[id$='rfvIDNumber']")[0], isReceiptRequired);
I just remembered that the last thing in the page-cycle is rendering it on the page so the jQuery can be manipulated by the values set in the control from code-behind.

Issues with "&" symbol in javascript

I have a aspx page from which some strings are passed into the Javascript function. I am facing a strange issue if the string contains a & symbol.
Here is the simplified version of the code
if(stringWhichComesFromUI == "AD&D")
{
//populate a hidden field
$('#hdnSomeHiddenField').value = "AD&D";
}
and in the UI, the hidden field value is populated in a cell inside a grid.
Now the problem is, even if user is sending "AD&D" from the UI, the variable stringWhichComesFromUI is becoming "AD&Amp;D" thats why the if block never executes.
I have also tried with
if(stringWhichComesFromUI == "AD&D" || stringWhichComesFromUI == "AD&Amp;D")
{
//populate a hidden field
$('#hdnSomeHiddenField').value = "AD&D";
}
This executes the if block, but the value which is going into the hidden field does not show properly in the UI. Value which is displayed in UI is "AD", the "&D" part is gone! I am not able to figure out why, please help?
There is error in syntax of assigning value in jquery. Use this
<asp:TextBox ID="myinput" runat="server" />
<asp:Button ID="SubmitButton" runat="server" OnClientClick="Showme()" Text="Submit" />
<asp:HiddenField ID="hiddenFieldText" runat="server" />
And your script will be like this:
function Showme(){
var stringWhichComesFromUI= $("#myinput").text();
if(stringWhichComesFromUI == "AD&D")
{
//populate a hidden field
$("#hiddenFieldText").val("AD&D");
}
}

How to call method of .aspx from .cs file

I created web page in that i used javascript in .aspx file.
I have a save-button,but in the source code i used javascript for save button, where i declared a function called OnClientClick="javascript : validateTextTest()" and in the head of source code i called this function validateTextTest().
Below is the save button in source code:
<asp:Button ID="Save" runat="server"
onclick="Save_Click" Text="Save"
OnClientClick="javascript : validateTextTest()" Width="63px" />
Now i need to call a function validateTextTest() in save button of .cs file.Because i have two to three textboxs, if i leave one texbox out of three textbox it should not insert into DB.
So please tell me how to call the function in .cs file.
Insted of doing such things , you can use asp.net validation controls , for your purpose you are going to need a RequieredFieldValidator for each one of your TextBoxes , and you can use them like following code :
<asp:TextBox ID="txtISBN" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RQVISBN" runat="server" ErrorMessage="*" ControlToValidate="txtISBN"></asp:RequiredFieldValidator>
These controls are greate ! And they do validation on clientSide as you want ;)
validateTextTest is your javascript function which you probably use for some client side validations before submitting to the server. So i dont think you really should use the client side function in your sever side code (.cs file) to validate the input. You should do the same validation inside your server side code also. Something like this
if((!String.IsNullOrEmpty(TextBox1.Text)) &&
(!String.IsNullOrEmpty(TextBox1.Text)) &&
(!String.IsNullOrEmpty(TextBox1.Text)))
{
// Insert to DB
}
else
{
//Show validation error message
}
You need to firstly start off by defining the technology stack you are using. Is it ASP.NET or MVC.
I am assuming you are using ASP.NET. Given the way you have already started writing this application. You will need to do a few things to get your approach to work.
<form name="myform">
<asp:HiddenField runat="server" id="validRequest"/>
<script type="text/javascript">
function validateTextTest() {
//validation goes here
var validRequest = document.getElementById(<%#validRequest.ClientID%>);
//set validation outcome to the validRequest etc
validRequest.value = 'true';
if(validRequest.value == 'true')
return true;
return false;
} </script>
</form>
I forget which one it is but check either your Page_Load etc
protected void Page_Load(object sender, EventArgs e)
{
if(validRequest.Value == "true")
//Do whatever you need to
}

Check result of ASP.Net validator clientside

I know the built-in ASP.Net validators come with a client-side framework, however I've been unable to find anything that lets me check a single validator for it's Valid state.
I expect it to be possible though, so I hope someone in here knows how to do it :-)
The validator in question is a RegularExpressionValidator, which I use to determine whether an e-mail address is valid or not.
Here's some brief code:
<script>
function CheckForExistingEmail()
{
Page_ClientValidate(); // Ensure client validation
if (revEmail.IsValid) // pseudo code!
{
// Perform server side lookup in DB for whether the e-mail exists.
}
}
</script>
<asp:TextBox runat="server" id="tbEmail" onblur="CheckForExistingEmail();" />
<asp:RegularExpressionValidator id="revEmail" runat="server" ControlToValidate="tbEmail" ErrorMessage="Not a valid e-mail address" ValidationExpression="([a-zA-Z0-9_\-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})" />
I found a way around it myself now:
By adding a ValidationGroup to the validator, I can use Page_ClientValidate(validationgroup) - which returns a bool value.
I'm not sure if it was the same thing you meant Pabuc, if it was please drop an answer and I'll obviously select that as the correct one :-)
Here's the code which works:
<script>
function CheckForExistingEmail()
{
if(Page_ClientValidate("email"))
{
// Perform server side lookup in DB for whether the e-mail exists.
}
}
</script>
<asp:TextBox runat="server" id="tbEmail" onblur="CheckForExistingEmail();" />
<asp:RegularExpressionValidator id="revEmail" runat="server" ValidationGroup="email" ControlToValidate="tbEmail" ErrorMessage="Not a valid e-mail address" ValidationExpression="([a-zA-Z0-9_\-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})" />
You can look at the visibility of the Validator message (we usually have a red Asterisk *)
if (document.getElementById("ctl00_ContentPlaceHolder1_revClientSite").style.visibility == "hidden") {
// validator says go ahead
} else {
alert("please fix the indicated field - it is not valid");
}
.style.visibility will be "hidden" or "visible"

Categories