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"
Related
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.
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
I have an ASP.NET project. Normally if I click search then it shows some results. Now I want after user search, it shows a prompt or window to ask for password first, if user enter the right pwd, it will open the full results, else if user choose not to enter pwd, it open another page which will show only a part of the result.
My plan is to use pwd checking in jsp:
<script src="../../../JS/Registration.js" language="javascript" type="text/javascript"></script>
But I don't know how to check what user choose here then redirect to different pages ?
aspx page
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
<asp:TextBox ID="password" runat="server"></asp:TextBox>
aspx.cs page code-behind
protected void Button1_Click(object sender, EventArgs e)
{
string pwd = password.Text;
//write your logic to check pwd and then redirect to other page here
}
let me know if you are still stuck somewhere
You need to make an ajax call to a C# function which will check the credentials. Then in success field, you can redirect to full results page and error field, specify the url of restricted results. You can look this post how to make an ajax call. I think Palash's answer may be most useful for you
Ajax Call
i have a String var in class
String message;
private int checkConstraints()
int a = 0;
if (docProcessId==0) {
a++;
message = "<script language=\"javascript\"> alert('Please Select Doc Process Name'); </script>";
}else if (refTypeName.equals("")) {
a++;
message = "<script> alert('Enter Reference Type Name!');</script>";
}
return a;
}
actually i am doing like this but when this method is called not equals to 0 then message equals to whole the string print on page not giving alert any solution please
JSF by default HTML-escapes all model values as part of XSS attack prevention. Your concrete problem suggests that you had no idea of that. You can "solve" it by using <h:outputText> with escape attribute set to false.
<h:outputText value="#{bean.message}" escape="false" />
However, your concrete problem is bigger. You're in JSF/MVC perspective basically making two major design mistakes here:
Writing HTML code in model instead of in the view.
Performing validation in an action method instead of in a validator.
You should be writing HTML code in the view, not in the model. You should be performing validation using a normal JSF validator. JSF has a lot of builtin validators.
Besides, not really a design mistake, but more an user experience mistake, there's a third mistake: using JavaScript alerts to show validation messages. This is simply too 1990 and Web 1.0. We're currently in 2013 and have learnt a lot, a lot of the user experience failures made back then. Using JavaScript alerts to show validation messages is one of them.
Here's the right approach using JSF-provided validation facilities:
<h:form>
<h:selectOneMenu value="#{bean.docProcessId}" required="true"
requiredMessage="Please Select Doc Process Name">
<f:selectItems ... />
</h:selectOneMenu>
<h:inputText value="#{bean.refTypeName}" required="true"
requiredMessage="Enter Reference Type Name" />
<h:commandButton value="submit" />
<h:messages />
</h:form>
That's it. The required="true" tells JSF that those inputs are required. The requiredMessage attribute allows you to specify custom messages for required validation. The messages will be displayed in place as declared by <h:messages>. You can customize the layout by layout attribute and by CSS means like infoClass, errorClass, etc. You can even manually loop over it and manually create annoying alerts for each message instead of using <h:messages>:
<ui:repeat value="#{facesContext.messageList}" var="message">
<script>alert("#{message.summary}");</script>
</ui:repeat>
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
}