ASP.NET Validate membership email from ClientSideEvents and WebMethod - asp.net

I have ASPxGridview and i want to check if email already registered before or not in editform using ClientSideEvents.
Any help to resolve this problem ?
aspx section
this is the javascript section
function OnEmailValidation(s, e) {
var error = "";
var tfld = trim(e.value);
var illegalChars = /^\w+([-+.'''']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
if (!illegalChars.test(tfld)) {
$get("spanEmail").innerHTML = "invalid email";
} else {
PageMethods.CheckEmail(e.value.toString(), OnCheckEmail);
// how to check OnCheckEmail before continue
//if(email already registered) {
// return false
//}
$get("spanEmail").innerHTML = "";
}
return true;
}
function OnCheckEmail(unavailable) {
if (unavailable == true) {
$get("spanEmail").innerHTML = "already registered";
$get("spanEmail").style.color = "red";
}
else if (unavailable != true) {
$get("spanEmail").innerHTML = "Available";
$get("spanEmail").style.color = "#76EB69";
}
}
aspx.cs
col_Email.PropertiesTextEdit.ClientSideEvents.Validation = "OnEmailValidation";
grid.Columns.Add(col_Email);
[WebMethod]
public static bool CheckEmail(string email)
{
System.Threading.Thread.Sleep(200);
if (Membership.FindUsersByEmail(email) != null)
{
if (Membership.FindUsersByEmail(email).Count <= 0)
{
return false;
}
return true;
}
else
{
return false;
}
}
This is my final code after the
Filip
advice but i have mini problem:
When i use
(async: false) and cntr.SetIsValid(false);
the control doesn't apply the action
but If i use
(async: true) and cntr.SetIsValid(false);
the control apply the action
Why ?
I want to use async: false
function OnEmailValidation(s, e) {
var illegalChars = /^\w+([-+.'''']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
var spanEmail = document.getElementById("spanEmail");
var obj = GetObj('txt_Email');
var cntr = aspxGetControlCollection().Get(obj.id);
if (!illegalChars.test(e.value)) {
spanEmail.innerHTML = "Invalid Email";
spanEmail.style.color = "red";
cntr.SetIsValid(false);
} else {
$.ajax({
type: "POST",
async: false,
url: "myweb_service.asmx/CheckEmail",
data: "{'email':'" + e.value.toString() + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(res) {
if (res.d == "true") {
spanEmail.innerHTML = "Email register before";
spanEmail.style.color = "red";
cntr.SetIsValid(false);
}
if (res.d == "false") {
spanEmail.innerHTML = "Available";
spanEmail.style.color = "#76EB69";
cntr.SetIsValid(true);
}
}
});
}}

You can use jQuery to call PageMethods (replace PageMethods.CheckEmail call with this code):
$.ajax({
type: "POST",
async: false,
url: "<PageName>.aspx/CheckEmail",
data: "{" + e.value.toString() + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(res) {
if (res.d)
return false;
}
});
Replace PageName with your page name.
Be careful with synchronous (async: false) ajax calls. They will block your page until request finishes.
If res.d doesn't return result or you just want detailed explanation of posted code check these links:
Using jQuery to directly call aspnet ajax page methods
A breaking change between versions of aspnet ajax

You will need to set up a web service on the server side that will check if the email already exists. Then you will use JavaScript AJAX (preferably a library like jQuery or Prototype) to query the web service during your validation method.
it will be a good deal of work to get it all set up. Good luck. See one of these links for more information:
http://msdn.microsoft.com/en-us/library/bb532367.aspx
http://msdn.microsoft.com/en-us/library/t745kdsh.aspx

Related

Check UserName availability by using AJAX in asp.net

I'm creating a SignUp form,i want to add a feature to the form in which whenever a new user types an username in the text box, it should automatically check if the username is already taken or not(should compare it with usernames exist in SQL server database). I want to implement this feature using AJAX.
Use the following jquery code, don't forget include jquery libraries
$("#<%=txtJournalIdToMove.ClientID %>").blur(function () {
var journalTextBoxId = '<%= this.txtJournalIdToMove.ClientID %>';
var journalId = $("#" + journalTextBoxId).val();
var params = '{"JournalId":"' + journalId + '"}';
$.ajax({
type: "POST",
url: "Default.aspx/PopulateVolumeNo",
data: params,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
// Replace the div's content with the page method's return.
var returnValue = data.d;
if (returnValue == null) {
alert("The given journal id does not exist or is in active in db.");
}
else {
//If success do your functionality
});
}
}
});
});
Try this onchange or on blur event of a textbox. Here I used user-name-box as text box id
$.post('/Server/CheckAvailablity/',
{name:function(){return $('#user-name-box').val()},
function(response){
if(response.status="Y"){
alert('available');
}
else{
alert('not available');
}
}
);
In server side CheckAvailablity method prepare a JSON object like {"status":"Y"} and return

Redirect from Webmethod in Asp.Net

Am new to Asp.Net Programming, Have just started a web project.
Am calling a WebMethod from Aspx page using JSON like below:
<script type="text/javascript">
function getLogin() {
var userName = document.getElementById('TextBox1').value;
$.ajax({
type: "POST",
url: "Services/LogService.asmx/authenticateLogin",
data: "{'userName':'" +userName.toString()+ "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert(response.d)
},
error: function (xhr, status, error) {
// alert(textStatus);
DisplayError(xhr);
}
});
}
function DisplayError(xhr) {
var msg = JSON.parse(xhr.responseText);
alert(msg.Message); }
</script>
And WebMethod :
[WebMethod]
public string authenticateLogin(string userName)
{
LoginBO loginBO = new LoginBO();
loginBO.userName = userName.ToString().Trim();
string result = "";
try
{
LoginDao loginDao = DAOFactory.GetDaoFactory().getLoginDao();
result = loginDao.selectUser(loginBO);
}
catch (DBConnectionException)
{
//result = "DB Conenction";
throw new Exception("DB Connection is Down");
}
catch (InvalidLoginException)
{
//HttpResponse res = new HttpResponse();
//HttpResponse.ReferenceEquals.Redirect("~/Login.aspx");
throw new InvalidLoginException("Login Is Invalid");
}
catch (Exception)
{
throw new Exception("Uanble to Fetch ");
}
int ctx = Context.Response.StatusCode;
return result;
}
After Successful Authentication, I want to redirect user to another aspx page.
What is the best practice to do ?
Thanks
Samuel
Add a redirect to the success section of your getLogin() function:
success:
function (response) {
alert(response.d);
windows.location.href = "http://url.for.redirect";
}
(Or use some other method for redirecting within jQuery/Javascript).
In your Ajax method
success: function(msg) {
alert(response.d);
window.location = "xyz.aspx";
},
success: function (response) {
alert(response.d)
window.location.href = "some.aspx";.
}
I think it will help you.

How to consume the return value of a webservice in jquery ajax call?

I have a simple webservice in asp.net which determine if the input parameter is valid or not :
[WebMethod]
public bool IsValidNationalCode(string input)
{
return input.IsNationalCode();
}
I call it from an aspx page by jquery ajax function :
$('#txtNationalCode').focusout(function () {
var webMethod = "../PMWebService.asmx/IsValidNationalCode";
var param = $('#txtNationalCode').val();
var parameters = "{input:" + param + "}";
$.ajax({
type: "POST",
url: webMethod,
data: parameters,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
if(msg.responseText == true)
$('#status').html("Valid");
else {
$('#status').html("Invalid");
}
},
error: function () {
$('#status').html("error occured");
}
});
});
But I don't know how to get the return value of webservice in order to show appropriate message . Here if(msg.responseText == true) doesn't work
Make the IsValidNationalCode method static and use this in javascript:
success: function (msg) {
if (msg.d == true)
$('#status').html("Valid");
else {
$('#status').html("Invalid");
}
}
For "d" explanation follow this link: Never worry about ASP.NET AJAX’s .d again

making ajax call (in jquery) for webservice in asp.net

I want to validate product code for duplication using ajax call(in jquery) for webservice in which web method is written. now if success function executes as 'duplicate product code' it should not allow the user to save record. so how can i check this on Save buttons click event
First, create the below method in the page code behind.
using System.Web.Services;
[WebMethod]
public static bool CheckDuplicateCode(string productCode)
{
bool isDuplicate = false;
int pCode = Convert.ToInt32(productCode);
//check pCode with database
List<int> productCodes = GetProductCodeInDb();
foreach (var code in productCodes)
{
if (pCode == code)
{
isDuplicate = true;
break;
}
}
return isDuplicate;
}
And in the page markup just before the end body tag insert this code
<script type="text/javascript">
$(document).ready(function () {
$('#<%=btnSave.ClientID %>').click(function () {
SaveProduct();
});
});
function SaveProduct() {
//Get all the data that you are trying to save
var pCode = $('#<%= txtProductCode.ClientID %>').val();
//pass the product code to web method to check for any duplicate
$.ajax({
type: "POST",
url: "/InsertProductPage.aspx/CheckDuplicateCode",
data: "{'productCode': '" + pCode + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
AjaxSuccees(msg);
},
error: AjaxFailed
});
}
function AjaxSuccees(msg) {
if (msg.d == true) {
return true;
//insert the rest of data
}
else {
alert("Product code already exists");
return false;
}
}
function AjaxFailed(msg) {
alert(result.status + ' ' + result.statusText);
}
</script>
Hope this helps

jQuery and ASP.NET Custom Validator

I'm trying to learn jQuery and it occurred to me that existing JS in some of my sites could be replaced with just a few lines of jQuery code. In the following code, I'm trying to set the value of a custom validator by making an AJAX call. The first block of code does not work as it should, whereas the second block works fine. The whole "if it ain't broke don't fix it" answer isn't helpful, I really want to learn jQuery. For the record, I've placed alerts in the code and they both return the exact same result, just one is setting the args and the other is not for some reason.
Why does this code NOT work:
function CheckForUserName(sender, args)
{
args.IsValid = true;
var url = "/somepage.aspx";
MakeCall(url, function(txt) {
if (txt == "false") {
args.IsValid = false;
}
});
}
function MakeCall(url,callback) {
$.ajax({
url: url,
dataType: "text",
success: callback
});
}
This code DOES work:
function CheckForUserName(sender, args)
{
args.IsValid = true;
var call = MakeCall();
if (call == "false")
{
args.IsValid = false;
}
}
function MakeCall()
{
var xmlHttp;
var validation=true;
xmlHttp=GetXmlHttpObject();
if (xmlHttp==null)
{
alert ("Your browser does not support AJAX!");
return;
}
var url="/somepage.aspx";
xmlHttp.onreadystatechange=function ()
{
if (xmlHttp.readyState==4)
{
if (xmlHttp.status==200)
{
return xmlHttp.responseText;
}
else
{
alert(xmlHttp.status);
}
}
};
xmlHttp.open("GET",url,false);
xmlHttp.send(null);
return xmlHttp.responseText;
}
function GetXmlHttpObject()
{
var xmlHttp=null;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}
In order to make it work, you need to specify the async option as false:
function MakeCall(url,callback) {
$.ajax({
async: false,
url: url,
dataType: "text",
success: callback
});
}
This works fyi.. ignore my custom javascript namespace functions, but you should get the concept.
<script type="text/javascript">
function VerifyCustomerNumber(s, a) {
var r = ProcessCustomerNumber(a.Value);
a.IsValid = r;
}
function ProcessCustomerNumber(n) {
var u = '/Services/WebServices/Customer.asmx/CountByCustomerNumber';
var d = '{"Number": "' + n + '"}';
$j.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: u,
cache: false,
async: false,
data: d,
dataType: "json",
success: function(r) {
var v = Data.JS.Ajax.ParseJSON(r);
return v;
}
});
}
</script>
Just for the record. Having a custom validator that allows AJAX calls is possible, but is a litle complicated. Here is an article about the issue.
Basically, one must do these things:
Say "Invalid!" immediately.
Show a "processing..." message instead of your "invalid" message.
Start your long-runing process, AKA your AJAX request.
As soon as your request ends, replace the ClientValidationFunction for a dummy function.
Reset the original message.
Update the validation state.
Reset the original validation function but only when the validated control changes.
Here is the final function that accomplishes the task (taken from the article):
//Create our respond functions...
var Respond_True = function (sender, args) { args.IsValid = true; };
var Respond_False = function (sender, args) { args.IsValid = false; };
function AjaxValidator(sender, args, ajaxSettings){
args.IsValid = false;
//This is a reference to our validator control
var $sender = $(sender);
//Save the original message, color and validation function to restore them later.
var originalMessage = $sender.text();
var originalColor = $sender.css("color");
var originalFunction = sender.clientvalidationfunction;
var validatedControl = $("#" + sender.controltovalidate);
//Change the error message for a friendlier one.
$sender.text("Checking...").css({ color: "black" });
var setRespondFunction = function (respondFunction) {
sender.clientvalidationfunction = respondFunction;
//Reconstitute original styles.
$sender.text(originalMessage).css({ color: originalColor });
//Re-validate our control
ValidatorValidate(sender, null, null);
ValidatorUpdateIsValid();
var onChange = function(){
//Reset the original validation function
sender.clientvalidationfunction = originalFunction;
//Re-validate to ensure the original validation function gets called
ValidatorValidate(sender, null, null);
ValidatorUpdateIsValid();
//Ensure the validation function is called just once.
validatedControl.unbind("change", onChange);
};
validatedControl.on("change", onChange);
}
var originalSuccessFunction = ajaxSettings.success;
//Start the AJAX call..
$.ajax($.extend(ajaxSettings, {
success: function(data){
setRespondFunction(originalSuccessFunction(data) ? "Respond_True" : "Respond_False");
}
}));
}
And here is a sample usage:
function MyJavascriptValidationFunctionName(sender, args){
AjaxValidator(sender, args, {
url: ...,
type: ...,
data: ...,
success: function(data){
return /*True or false*/;
}
});
}

Resources