I have this JavaScript code that only allows users to enter letters and white space. If I allow that, the user can now enter the name as white space only and it will go to the database. Is there a way to prevent the user from entering white space only and force them to add letters?
And an optional question, can I prevent the user from entering two white spaces?
<script>
function lettersOnly(input) {
var regex = /[^a-z & " "]/gi;
input.value = input.value.replace(regex, "");
}
</script>
<input id="fullname" placeholder="fullname" onkeyup="lettersOnly(this)">
You could just leave your code as is and when the user submits the form, you get rid of any whitespace. Something like:
string.replace(/\s/g,'')
The \s character matches ANY number of whitespaces, so that also solves your problem of preventing the user from entering two or more whitespaces.
However, if having whitespace in the name is a real problem, you should consider doing this on the back-end, to prevent the possibility of people bypassing your regex replace and inserting unwanted values into the DB.
Try this regex, and it will allow for one whitespace only. Otherwise, it will be removed.
var regex = /\s\s+/gi;
input.value = input.value.replace(regex, "");
And if you need to remove all whitespaces, you can try
input.value.replace(/\s/g,'')
Just add a following check condition before invoking service.
input.trim() !=== ""
It's possible to pretty easily prevent only whitespace, use .charAt() to check if the first character is whitespace.
if the entire string is whitespace, then your first character is definitely whitespace.
Example:
if (input.value.charAt(0) == " ") {
//Do your things
}
As far as checking whether or not two immediately adjacent spaces are present, you can do that with regEx relatively easily, using an expression like [ ]{2,}.
In all seriousness, you're probably better off using a well-known, predefined form-validation library for the time being.
To avoid only white spaces given as input
Just add the following check condition
If ( input.trim() == "" ){
Expression
}
Related
I am trying to do a validation on a textbox value with jquery to make sure textbox accepts only alpha numeric values. I am also trying to allow spaces between words. I am not trying to allow spaces to left and right of the sentence in textbox. how can I allow spaces in middle of words in the textbox?
My trails fiddle
$('#dsTest').keyup(function() {
if (this.value.match(/[^a-zA-Z0-9]/g)) {
this.value = this.value.replace(/[^a-zA-Z0-9]/g, '');
}
});
You're not going to be able to do it gracefully using only keyup, because while still in the process of typing the sentence, the space you just typed (intending it to be in the middle) is at the end.
Instead, I would do something like this:
$('#dsTest').keyup(function() {
if (this.value.match(/[^a-zA-Z0-9 ]/g)) {
this.value = this.value.replace(/[^a-zA-Z0-9 ]/g, '');
}
});
$('#dsTest').focusout(function() {
this.value = this.value.trim();
});
Allow spaces to be typed while typing is in progress, and strip the leading and trailing spaces with String.trim() at some reasonable later point. In my example, I use .focusout(), but you could also just trim when consuming the value.
This is an example of a broader category of validation problems in which testing WHILE input is being entered prevents the user from entering a value that would have been legal once they were done - because entering the value one character at a time requires the value to temporarily have an invalid state. There are two main ways of handling that problem:
Don't test for validation until the user has finished inputting the value
Flag invalid values rather than altering them
You can also combine the two - for instance, highlighting the field while the user is typing to show that the current value is invalid, and then also fixing the value to make it valid if they leave the field while the invalid value is still present.
In pure regex this should work /^[a-zA-Z0-9]+[a-zA-Z0-9\s]*[a-zA-Z0-9]+$/g. Note that this would requires at least 2 characters in the value. If you want to also allow it to be blank then you could do /^([a-zA-Z0-9]+[a-zA-Z0-9\s]*[a-zA-Z0-9]+|)$/.
With all that said, it is prob better usability-wise to just trim the value, as mentioned by other answers, since that does not stop the user from moving forward if they accidentally add a leading or trailing space.
I am trying to validate string which can take only alphanumeric values without space.
str.replace(/[^a-zA-Z0-9\u00E0-\u00FC ]+/gi, '')
I used above code but seems still it is taking white space. Did not able to find the right way to fix it.
Remove the space in regexp
str.replace(/[^a-zA-Z0-9\u00E0-\u00FC]+/gi, '')
// ---------------------------------^ here
What I am trying to do is clean up an input field on blur. My blur code is completely functional, but I can't get the regex to work correctly. All of the characters I'm trying to allow are working correctly except for any number of line breaks. I've tried with different variations and combinations of including /s, /r, and /n .
I am doing this because I want to prevent as many characters that don't really belong in a descriptive input field as possible. I am using entity to linq for database input, which should protect me from sql injection attacks, but I still want to restrict the characters for added security. I am allowing apostrophes, but that should be the only potential threat from the allowed characters listed in the regex below.
Once I get the regex, I'll also replace on paste using the same code block.
This is my javascript method that I reverted back to.
function CleanSentenceInput(AlphaNumString) {
input = AlphaNumString;
var CleanInput = input.replace(/[^a-z0-9\s.,;:'()-]/gi, '');
CleanInput = myTrim(CleanInput);
return CleanInput;
}
Is there a way to allow any number of line breaks by modifying this replace regex?
Test Input:
aaaaaaaaaaaaaaa
bbbbbbbbbbbbbbbb
cccccccccccccccc
cccccccccccccccc
Test Result:
aaaaaaaaaaaaaaa
bbbbbbbbbbbbbbbbcccccccccccccccccccccccccccccccc
Expected Result:
aaaaaaaaaaaaaaa
bbbbbbbbbbbbbbbb
cccccccccccccccc
cccccccccccccccc
Update ** It turns out that the trim function I was using was removing the line-breaks. Here is that function:
Bad trim function:
function myTrim(x) {
return x.replace(/^\s+|\s+$/gm, '');
}
Is there a way to fix this regex so that it still replaces whitespace before and after, but not inside of the content?
Updated **
Good Trim Function:
function myTrim(x) {
return x.replace(/^\s+|\s+$/g, '');
}
As I noted from the beginning the problem is not with the regex since
/[^a-z0-9\s.,;:'()-]/gi
matches characters other than whitespace (beside others in the character class).
In MyTrim you need to remove m because otherwise, $ is treated as a line end and ^ as line start anchors, and in fact you want to only trim the string from its beginning and end:
function myTrim(x) {
return x.replace(/^\s+|\s+$/g, '');
}
It is also possible to use trim() (it is supported by all modern browsers, IE9 already should support it).
I've an HTML field in a form and, using JS and Regex, I must restrict the characters the user can insert in the field. The user of the form can only insert the following characters ( ) * + ^ / X x, and numbers and spaces (when he digits or pastes a different character nothing is written). Is this possible? I need the Regex, I eventually know how to do with JS.
Try this regex
[^\(\)\*+\^/Xx0-9 ]
Here we are trying to find a pattern which contains none of the allowed characters. If you find it this means that the character entered was wrong.
There is no right or wrong answer to this.
Usually it is less expensive to check using the bias of the logic for the particular condition.
If it sounds better saying whats allowed, then use the allowed (positive) character class.
Allowed class: [()*+^/Xx0-9 ], Checks: <space> (-+ /-9 X \^ x
Not allowed class: [^()*+^/Xx0-9 ], Checks: \0-\37 !-' , \- . :-W Y-\] _-w y-\377
Statistically, if %99 of the data enterred were valid, the 'Allowed' class would do less work in that
not every character or range has to be checked.
Where the 'Not-Allowed' class will have to check every range.
In this particular case, the negative class has many more ranges and characters to check, its borderline
more efficient if most of the data were invalid,
With regard to:
[^\(\)\*+\^/Xx0-9 ]
None of those characters need to be escaped inside a set (but it is okay to do so).
If you want to restrict as the user types (this uses jquery methods):
$('#in1').keyup(function (evt) {
var content = $('#in1').val();
$('#in1').val(content.replace(/[^()*+^/Xx0-9]/g, ""));
return true;
});
Where 'in1' is the id of the input.
$('#customerAddress').text().replace(/\xA0/,"").replace(/\s+/," ");
Going after the value in a span (id=customerAddress) and I'd like to reduce all sections of whitespace to a single whitespace. The /\s+/ whould work except this app gets some character 160's between street address and state/zip
What is a better way to write this? this does not currently work.
UPDATE:
I have figured out that
$('.customerAddress').text().replace(/\s+/g," ");
clears the 160s and the spaces.
But how would I write a regex to just go after the 160s?
$('.customerAddress').text().replace(String.fromCharCode(160)," ");
didn't even work.
Note: I'm testing in Firefox / Firebug
Regarding just replacing char 160, you forgot to make a global regex, so you are only replacing the first match. Try this:
$('.customerAddress').text()
.replace(new RegExp(String.fromCharCode(160),"g")," ");
Or even simpler, use your Hex example in your question with the global flag
$('.customerAddress').text().replace(/\xA0/g," ");
\s does already contain the character U+00A0:
[\t\n\v\f\r \u00a0\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u2028\u2029\u3000]
But you should add the g modifier to replace globally:
$('#customerAddress').text().replace(/\s+/g, " ")
Otherwise only the first match will be replaced.
Sorry if I'm being obvious (or wrong), but doesn't .text() when called w/o parameters just RETURNS the text? I mean, I don't know if you included the full code or just an excerpt, but to really replace the span you should do it like:
var t = $('#customerAddress').text().replace(/\xA0/,"").replace(/\s+/," ");
$('#customerAddress').text(t);
Other than that, the regex for collapsing the spaces seems OK, I'm just not sure about the syntax of your non-printable char there.