简体   繁体   中英

How to trim string in ClientValidationFunction

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!

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.

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, "" );
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM