How to trim string in ClientValidationFunction

a 夏天 提交于 2020-01-06 06:38:47

问题


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:


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.




回答2:


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



回答3:


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.



来源:https://stackoverflow.com/questions/343111/how-to-trim-string-in-clientvalidationfunction

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!