Validating partial page with ASP.NET Validators using JavaScript

Validation plays a key role whenever we take a inputs from the user. For this, ASP.NET provides us few validator controls that are used a lot in web applications.
Now a days, in our application, we used to have several section in our web pages.
And also, we populate some data based on the user’s input.
So several times, it requires  to validate the page partially not the entire page,
while earlier we used to have single submit button and their we need to validate the page.

AJAX also played a key role, for partial post back, initiate a call to server etc, which requires to validate a part of the page.

So in these scenarios our earlier approach of validation would not work.
In this kind of scenario, I will discuss few things that will be very helpful.

First, I would suggest, to divide your page in some logical section, those you might need to validate at certain points. And assign a different group name to the validators on those section.

1) If you are initiating an ajax call or initiating a callback from java-script, and you want to validate certain section/part of the page.

So before initiating the ajax call, you need to validate the user inputs. This can be easily with the following method.

You need to call Page_ClientValidate() method, this method has two flavors,
– Page_ClientValidate() it fires all the validators on the page and returns false, if it fails
– Page_ClientValidate(‘groupname’), this method fires all the validators having the passed groupname and returns false if any validator fails.
This is quite useful, while validating partial section/part of the page. So your java script code may look like this

function SaveAddress()
{
	if(Page_ClientValidate('groupname') == false)
		return false;
	else
	{
		//Save Address
	}
}

2) Several time, it happens, that based on some requirement, we used to hide some section of input form or hide some input control, but whenever page/section is going to be submitted, the hidden validators also gets fired. So to overcome this problem, you may need to disable the validators. So to disable any validator from javascript as

document.getElementById('ValidatorClientId').enabled=false;

So these validator wont be fired till you gain enable it. You can enable it as

document.getElementById('ValidatorClientId').enabled=true;

Hope you all will like this post and will found it to be useful.

Why MaxLength property of a textbox with multiline mode doesn’t work? A Solution

Many developers set the MaxLength property of a Textbox and it works fine until the Textbox is not in multiline mode, which is by default behavior of a Textbox.

So what is the basic diffference between a textbox in single line and multiline mode!!!

Let’s see, how it gets rendered as html. Lets have a look

Textbox with SingleLine mode

Textbox with SingleLine mode

Now Textbox with MultiLine mode

Textbox with MultiLine mode

Textbox with MultiLine mode

As you can see, When a Textbox is in SingleLine mode, it gets rendered as a input type text  and when it is in MultiLine mode, it gets rendered as a textarea. As we know MaxLength property works only for input type.

So what is the solution. We need to have a custom solution for this.

Let’s try some solution,

One thing we can do, we can attach a function on onkeypress event to the textbox, which first check the length of input string and if exceed with limit it just returns else allow to enter any input. In the below example I have used the maximum length as 10.

<asp:TextBox ID="tb" runat="server" TextMode="MultiLine" onkeypress="return CheckLength();"></asp:TextBox>

//And the javascript code is
function CheckLength() {
            var textbox = document.getElementById("<%=tb.ClientID%>").value;
            if (textbox.trim().length >= 10) {
                return false;
            }
            else {
                return true;
            }
        }

This works fine until, a user doesn’t paste a text  which is greater than the max length that is given( here 10).  So there is no simple way to stop this. To overcome this problem, one should use one of the asp.net validators.

One can go for the custom validator, and provide a javascript function, which checks the length of the text and if exceeds the maxlength then show an error. Let’s see the code below

<asp:TextBox ID="tb" runat="server" TextMode="MultiLine" ></asp:TextBox>
//Validator
        <asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="Please enter maximum 10 charachters." ControlToValidate="tb"
         SetFocusOnError="true" ClientValidationFunction="CheckMaxLength" ></asp:CustomValidator>

//Client Validator function
function CheckMaxLength(sender, args) {
            if (args.Value.trim().length >= 10) {
                args.IsValid = false;
            }
        }

But there is another smart way is there, to acheive this. We can also use Regular expression validator for this, which will check the count of the entered character and will throw an error if it exceeds. Here we would not require to write a javascript function. We need to have a regular expression that will work. Let’s see the code

<asp:TextBox ID="tb" runat="server" TextMode="MultiLine" ></asp:TextBox>

//Regular Expression validator
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ControlToValidate="tb" ErrorMessage="Please enter maximum 10 charachters."
 SetFocusOnError="true" ValidationExpression="^[a-zA-Z.]{0,10}$"></asp:RegularExpressionValidator>

Here we don’t require to write a javascript function. I have used a regular expression ^[a-zA-Z.]{0,10}$, which allows all the characters with length 0 to 10.

Hope you all must have enjoyed.

Thanks,

Brij