views:

556

answers:

3

I am writing a client-side validation function for CustomValidator and I need to check length of entered string. But before, to counteract cheaters a little, I want to remove all leading and trailing spaces from the string. What is the easiest way to do it in this scenario?

Thank you!

+1  A: 

Forgive me for being obtuse, but are you simply looking for a trim function in Javascript? If so, here's what jQuery uses:

function trim( text ) {
 return (text || "").replace( /^\s+|\s+$/g, "" );
}
J Cooper
+1  A: 

The easiest way is to call the ValidatorTrim(value) javascript function on your page. This function comes from the javascript that every asp.net validator includes when added to a page.

But i don't think its a documented feature, so you cant rely on it being available in future versions of the validators. So i would prolly go through jQuery, or add your own function as J Cooper points out.

Tom Jelen
You are very right! :)
Alexander Prokofyev
A: 

Have to say the question I asked could be easy googled, and I have already investigated it. But I want to contribute to StackOverflow community a solution which is the simplest if you are writing a client validation function for a ASP.NET page.

It's known what RequiredFieldValidator also trims spaces of a string to be checked. If you look into the source of ScriptResource.axd file associated with your application, you can find this

function RequiredFieldValidatorEvaluateIsValid(val) {
    return (ValidatorTrim(ValidatorGetValue(val.controltovalidate)) != 
        ValidatorTrim(val.initialvalue))
}

and more interesting this

function ValidatorTrim(s) {
    var m = s.match(/^\s*(\S+(\s+\S+)*)\s*$/);
    return (m == null) ? "" : m[1];
}

code fragments.

So, you shouldn't rewrite trim function from the scratch, you already have it and can use it.

Alexander Prokofyev