0
votes

I have a webform application.

On client side I use custom JavaScript validation to hightlight a textbox and show a validation messages when the text is changed or a submit button is clicked.

The server side validations take place on Submit. It brings back a list of messages (string) to prevent the system saving the form.

The client validation are generic e.g. check “required field”, “word limited”, while the server validation need to work with data record, e.g. “existing name”, “User has to specify option ‘A’ when there are related records in table B.”

The shortcoming of the server side validation is that it only brings back a message summary, but cannot show the msg beside textbox. (how does the server side know each control id or where to show each msg?)

How does server side and client side validation work together in order to show the msg upon each textbox? Any nice designs or architectures for .net ? For sure all client side validation will be duplicated in server side any way.

Thx

2

2 Answers

2
votes

IMO ASP.NET Validators are very nice, you can check validators on server side with Page.IsValid.

If you wont check on server value for each control and display message box or whatever then you can use CustomValidator and call some server side method with ajax and use that for validation.

Here is the example of JavaScript function for CustomValidator calling server side ashx handler to check is mail address valid, this is a just example and you can use other methods that ASP.NET offers for calling server side (services, page methods etc.)

JUST A NOTE : THIS IS NOT REPLACEMENT FOR SERVER SIDE VALIDATION, you still need that too becouse this can be easily avoided.

function IsEmailValid(val, args) {

  var strUrl = "/SiteHandler.ashx?CheckEmail=" + args.Value;
  var strReturn = "";

  $.ajax({
           url: strUrl, 
           success: function (html) { strReturn = html; }, 
           async: false
         });

  args.IsValid = strReturn == "true";
}

Set that function to custom validator :

customValidator.ClientValidationFunction = "IsEmailValid";

On server side in ashx handler :

public void ProcessRequest(HttpContext context)
{
  if (context.Request.Params["CheckEmail"] != null)
  {
    if (CallSomeCustomLogicAndReturnIsMailOK(context.Request.Params[CheckEmail]))
      context.Response.Write("true");
    else
      context.Response.Write("false");
  }
}
1
votes

A good solution would be to use AJAX to submit the form. You could use one of many libraries available, or extend your custom javascript solution to implement it. If the server validation fails, you can connect to display the same messages as the client validation. You are correct to say that in both cases the messages should be the same. The user doesn't care if the validation failed in server or client side.