Compare array of words to a textarea input with javascript - php

I have a textarea inside a form.
Before the form is submitted, the textarea is validated and checked so it is not empty, not over 2000 characters, not contain forbidden characters etc...
I am working on the last part of the validation, which would need the textarea to be compared to an array of "bad words".
This to help me maintain and keep a good "language" on my site.
I am not very good on js, so does anybody know of a way to compare each word of the textarea to the array of bad words?
Also, would this slow down the validation much? (the array contains at most 100 words).
Thanks

If you wanted to check for the presence of "expletive1" and "expletive2" you'd do the following:
my_textarea = document.getElementById('textarea_id');
if (/\b(?=\w)(expletive1|expletive2)\b(?!\w)/i.test(my_textarea.value)) {
// we found bad words! do something
} else {
// no bad words found, carry on, nothing to see here
}
And you'd just add more words to the list in the same manner (expletive1|expletive2|expletive3|expletive4)
Keep in mind that to keep the words out of your app entirely you'll also need to do server-side filtering.

var bad_words = ['stupid', 'dang']; // watered down
for (var i = 0; i <= bad_words.length; i++) {
if (document.getElementById('my_textarea').value.match(bad_words[i])) {
// has bad word!
}
}
This will keep your code a bit neater, because you don't have to have 100 words in one regex match.

This code replaces bad words with *****
// creating regex
var words = ['bad', 'words'];
var wordsStr = "";
for(var i=0; i<words.length; i++) {
wordsStr += words[i];
if (i < words.length -1) {
wordsStr += "|";
}
}
// wordsStr is "bad|words"
var regex = new RegExp(wordsStr, "gi"); // g: replace all; i:insensitive
// replacing
var text = "I cant say bad words!";
text = text.replace(regex, "****");
// text is "I cant say **** ****!"
See in jsfiddle

var bad_words = new Array('word1', 'word2');
var user_words = document.getElementById('textarea').split(/\W+/);
for( var i in bad_words)
{
if( user_words.indexOf( bad_words[i] ) != -1 )
{
alert( 'The textarea has bad word!');
break;
}
}

You can downvote me if you want, but maybe just don't make the clbuttic mistake of trying to filter in the first place :D

Related

Use JavaScript to prevent spacebar?

I have a live search on a site I'm developing. At the moment, it searches the MySql database after the first character is typed, and updates the search for each new character. When Space is pressed as the first character, it displays all entries in the database. I don't want it to do that. I have the following code that I found somewhere that prevents the SPACE character from being typed:
$('input[type="text"]').keydown(function(e){
var ignore_key_codes = [8,32];
if ($.inArray(e.keyCode, ignore_key_codes) >= 0){
e.preventDefault();
}
});
This does what it's meant to do, but not exactly what I want. This will prevent the space bar from working in the text input at all, what I require is that it only prevents the space bar if it's the first character being typed. For example, typing " apples" would prevent the space, but typing "apples oranges" wouldn't.
Is there anything I can try to achieve this?
You can do it easily like this example:
function keyPress(e) {
var e = window.event || e;
var key = e.keyCode;
//space pressed
if (key == 32) { //space
return;
}
searchInDataBase(); //make your ajax call to search in data base etc.
}
If the space key is pressed, you return and dont do nothing, otherwise you continue in your search...
$('input[type="text"]').keydown(function(e){
if (e.keyCode == 32 && $.trim($(this).val()) == ''){
e.preventDefault();
} else {
alert("searching..");
}
});
Demo: http://jsfiddle.net/BerkerYuceer/JJG9M/
Following on from #Florent's comment, when a user types a value into your textbox,check if the trimmed value is != '' if so it should be safe to continue
e.g
if($.trim($txtbox.val()) != ''){ // proceed to do search
}

JS or PHP Add Leading Zero to Decimals

I have a form that I'm trying to automatically enforce decimals in some of the input fields. Basically I would like for the users to not worry about format, but simply have the fields format themselves onBlur.
Here are a few examples of what I'm hoping to achieve:
1.) If a user enters "0.95" nothing is done, because this is the ultimate format I'm going for in the end.
2.) If a user enters ".95" I would like for the field onBlur to change to the above format "0.95". (likewise if they enter ".9" etc)
I have been scouring around on the internet all night long looking for a solution, so this is my last resort! Any help and feedback I can get would be more than appreciated!
Thank you!
Something like this would do it:
document.getElementById('amount').onblur = function() {
if(this.value && !isNaN(this.value)) {
this.value = parseFloat(this.value).toFixed(2);
} else {
this.value = 0;
}
};
jsFiddle
This is nice and concise:
function blurFormatDecimal (e) {
var val = isFinite(this.value) ? +this.value : 0;
this.value = val.toFixed(2);
}
myInput.onblur = blurFormatDecimal;
Use isFinite() instead of !isNaN() because isNaN("Infinity") returns false, but you certainly don't want to accept "Infinity" as valid input.
http://jsfiddle.net/gilly3/NjeQD/
If you need to do this with PHP try:
$formattedAmount = sprintf("%05.2f",$amount);
Here is the php solution:
$formattedAmount = sprintf("%01.2f",$amount);

Spliting Text Nicely over Multiple Lines (i.e. for titles)

I'm fighting over a way to have text wrap nicely to fit into set div boxes. Browsers wrap the text if it's too long to fit on one line which is expected, but this can often lead to rather nasty looking presentation.
For example, this looks fine:
This is the title
But if I have a longer title, it may end up wrapped like this:
This is a slightly longer
title
As you can see the second one doesn't really look very nice, what I'm aiming for is something like this:
This is a nicer
wrapped title
I know how big the containing DIV will be, so that's not a problematic variable, but I'm trying to wrap my mind around all the possible ways of achieving nicely formatted titles and their flaws. So the question is, what would be the best way of doing this? I can think of a few ways, but they start to get exponentially more complicated if it wraps over more than 2 lines.
EDIT:
I'm currently using this - https://xnode.org/paste/19 - to try and even out the split lines, although I'm sure it's far from perfect.
You can remove the newlines and then use wordwrap function
Sounds like a job for the wordwrap function http://php.net/manual/en/function.wordwrap.php
Try using wordwrap function and give this CSS for the DIV:
div {
text-align: justify;
}
If http://fittextjs.com/ doesn't do the trick, try something along these lines...
Count the characters in your title and decide if it is going to need 1 line, 2 lines 3 lines, etc. (there will be some trial & error involved)
Replace all the spaces apart from where you want line breaks with (non-breaking spaces) and let the browser do the word wrapping.
In other words, in your This is a nicer wrapped title example, there are 29 letters, so you need a break around half way or just after, so replace the first non-breaking space after position 14 or 15 with a regular space ie between 'nicer' and 'wrapped', and that should do the job. Same thing in thirds or quarters for longer lines.
Sorry no code but from the examples you gave above you should be ok coming up with your own implementation.
I've created this jQuery plugin that does what you want
$.fn.prettyBreak = function () {
return this.each(function () {
var element = $(this);
var elementLineHeight = element.css("line-height").replace("px", "");
var elementContent = element.contents();
element.wrapInner("<span style='white-space: nowrap'>");
element.find("br").remove();
var textWidth = element.find("span").width();
element.html(elementContent);
var elementText = $.trim(element.text());
if (element.is(":visible") && textWidth > element.width() && element.height() < elementLineHeight * 2.1) {
var middle = Math.floor(elementText.length / 2);
var before = elementText.lastIndexOf(" ", middle);
var after = elementText.indexOf(" ", middle + 1);
if (middle - before < after - middle) {
middle = before;
} else {
middle = after;
}
var s1 = elementText.substr(0, middle);
var s2 = elementText.substr(middle + 1);
element.html(s1 + "<br> " + s2); // note the space after the tag
} else {
element.html(elementText);
}
if (element.is(":visible")) {
element.css("opacity", 1);
}
});
}
Usage:
$(document).on("ready", function () {
$(".pretty-break:visible").prettyBreak();
setInterval(function () {
$(".pretty-break:visible").prettyBreak();
}, 1000);
});
Github link: https://github.com/SumoSoft/PrettyBreak

Chinese character forbid

I have a web form, and I'd want the user while filling the form to not include any Chinese single quotes/double quotes in a textarea, how can I do that ?
You could get the form content and check it against a list of non accepted characters:
$formContent = $_GET["formcontent"];
$badCharacters = array("'", "‘", "“");
$cleanResult = str_replace($badCharacters, "", $formContent);
The bad characters array has the quote signs you dont like (if they are the standard quotes you will need to escape them) then the str_replace function goes through the form data replacing each one with an empty string. You should do proper escaping and security before this of course.
To prevent user from typing into form element you must use client side scripting aka JavaScript.
Simple way is handling the onkeypress event:
<textarea onkeypress="return CheckKey(event);"></textarea>​
And having such code:
var arrForbiddenCodes = [97, 98, 99];
function CheckKey(event) {
var keyCode = event.keyCode || event.which;
for (var i = 0; i < arrForbiddenCodes.length; i++) {
if (arrForbiddenCodes[i] === keyCode)
return false;
}
return true;
}​
This will block characters based on their key code - in the above code, the lower case "a", "b" and "c" letters will be blocked. To find key code of specific character, add alert(keyCode); to the function and just type that character into the textarea.
Live test case.
you could add some javascript that uses a regex to restrict the entry to alpha or alpha and numeric (or any additional characters you want).
<script language="javascript">
function blockChar()
{
var str = document.getElementById('txt').value;
if(str.match(^[a-zA-Z0-9]*$)) {
return true;
}
else {
return false;
}
}
</script>

Regex replace part of url with string only when url doesn't start with http://

Tried to find the answer on stackoverflow but I'm a complete RegEx noob!
All I need (if it's possible) is to match a PDF URL in some HTML and if it doesn't start with http:// add /content/ to the start, if it does start with http:// do nothing.
The regex you want is probably
http://add/content/\S+?\.pdf
Which says it must start with "http://add/content/" then can have anything which isn't a whitespace until it hits a .pdf at the end.
Depending on what language you use you will need to apply this differently. For example in php it would be
preg_match_all('|http://add/content/\S+?\.pdf|',$html,$matches);
if(count($matches)) {
//do stuff with the matches in the $matches array
} else {
//there were no matches of that form
}
Assuming you want to do this with javascript.
var links = document.getElementsByTagName("a");
for(var i = 0; i < links.length; i++){
var link = links[i];
var href = link.getAttribute("href");
if(!/^http/.test(href))
{
link.setAttribute("href", "/content/" + href);
}
}

Categories