How to trim a string in ClientValidationFunction

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

Thanks!

0
source share
4 answers

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

But I do not consider it a documented function, so you cannot rely on its availability in future versions of validators. That way, I would crawl through jQuery or add your own function, as J Cooper points out.

+4
source

Excuse me for being stupid, but are you just looking for a trim function in Javascript? If so, here is what jQuery uses:

 function trim( text ) { return (text || "").replace( /^\s+|\s+$/g, "" ); } 
+2
source

I must say that the question I asked can be easily run, and I have already researched it. But I want to contribute to the StackOverflow community - this is the easiest solution if you write a client validation function for an ASP.NET page.

RequiredFieldValidator is also known to trim the whitespace of a string that needs to be checked. If you look at the source of the 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 is

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

code snippets.

So, you should not rewrite the trimmer function from scratch, you already have it and can use it.

0
source

To add to the Cooper jQuery option above, here is the same from Angular:

 var trim = function(value) { return isString(value) ? value.trim() : value; }; 
0
source

Source: https://habr.com/ru/post/889167/


All Articles