How can I prevent users from inserting certain words in a form on my website? Even though my code detects these words and displays a popup message, the form still submits the data once the user acknowledges the message. The strange behavior has me puzzled. Below is the code snippet:
HTML Form
<form name="form1" action="#" method="post" required>
<label>Line 1: </label>
<input type="text" name="firstline" required onClick="select_area()"><br/>
<label>Line 2: </label>
<input type="text" name="secondline" required onClick="select_area2()"><br/>
<label>Line 3: </label>
<input type="text" name="thirdline" required onClick="select_area3()"><br/>
<input type="submit" name="submit_btn" id="submit" value="Submit" onClick="validate_text();">
<input type="reset" id="reset" value="Reset">
</form>
JavaScript File
var swear_words_arr=new Array("word1","word2","word3");
var swear_alert_arr=new Array;
var swear_alert_count=0;
function reset_alert_count()
{
swear_alert_count=0;
}
function validate_text()
{
reset_alert_count();
var compare_text=document.form1.firstline.value;
for(var i=0; i<swear_words_arr.length; i++) {
for(var j=0; j<(compare_text.length); j++) {
if(swear_words_arr[i]==compare_text.substring(j,(j+swear_words_arr[i].length)).toLowerCase())
{
swear_alert_arr[swear_alert_count]=compare_text.substring(j,(j+swear_words_arr[i].length));
swear_alert_count++;
}
}
}
var compare_text=document.form1.secondline.value;
for(var i=0; i<swear_words_arr.length; i++) {
for(var j=0; j<(compare_text.length); j++) {
if(swear_words_arr[i]==compare_text.substring(j,(j+swear_words_arr[i].length)).toLowerCase())
{
swear_alert_arr[swear_alert_count]=compare_text.substring(j,(j+swear_words_arr[i].length));
swear_alert_count++;
}
}
}
var compare_text=document.form1.thirdline.value;
for(var i=0; i<swear_words_arr.length; i++) {
for(var j=0; j<(compare_text.length); j++) {
if(swear_words_arr[i]==compare_text.substring(j,(j+swear_words_arr[i].length)).toLowerCase())
{
swear_alert_arr[swear_alert_count]=compare_text.substring(j,(j+swear_words_arr[i].length));
swear_alert_count++;
}
}
}
var alert_text="";
for(var k=1; k<=swear_alert_count; k++){
alert_text+="\n" + "(" + k + ") " + swear_alert_arr[k-1];
}
if(swear_alert_count>0) {
alert("The message will not be sent!!!\nThe following illegal words were found:\n_______________________________\n" + alert_text + "\n_______________________________");
document.form1.text.select();
} else {
document.form1.submit();
}
}
function select_area()
{
document.form1.firstline.select();
}
function select_area2()
{
document.form1.secondline.select();
}
function select_area3()
{
document.form1.thirdline.select();
}
window.onload=reset_alert_count;