How to prevent submit if user inputs a link? - javascript

I have run into a bit of a problem recently.
I am still in the process of learning JS so i couldn't figure this one out alone :( .
I have been getting a lot of spam recently through this form I have on a website and I cant seem to fix it...I tried a few solutions with Jquery and JS but I cant get it to work so I just deleted them.
100% of the spam I receive has a link in the message so I would like to make it so the submit button stay disabled unless 2 conditions are met :
The message must contain more than 12 characters
The textarea must NOT contain any link
here is the html i got :
<form action="php/contact.php" method="POST">
<h1>Contact-us</h1>
<input type="text" id="name" name="name" placeholder="Name" required>
<input type="email" id="email" name="email" placeholder="Email" required>
<input type="tel" id="tel" name="tel" placeholder="Phone" required>
<input type="text" class="subject" id="subject" name="subject" placeholder="Subject" required>
<textarea name="message" id="messag" class="textarea" placeholder="Message" required></textarea>
<button type="submit" class="submit" name="submit" id="disabled">Send</button>
</form>
also I am preventing a page refresh using ajax, and any JS i tried would conflict or be ignored by the ajax request, here is the code :
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: '/php/contact.php',
data: $('form').serialize(),
success: function () {
alert('Your message was sent successfully');
}
});
});
});
a fairly simple form i think...any help is greatly appreciated !
Thanks

You can probably check to make sure that the body of the message sent by the user doesn't have a link using a regex to match links.
The regex I used was taken directly from the answer of this question: Detect URLs in text with JavaScript
$("#my-form").on("submit", ev => {
ev.preventDefault();
const urlRegex = /(https?:\/\/[^\s]+)/gm;
const message = $("#message-field").val();
if(! message.match(urlRegex)){
// you can send the message with ajax
// ...ajax code
alert("message sent");
} else {
// there was a link in the message, give a warning or something
alert("link detected");
}
});
<!-- Import JQuery -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="my-form">
<p>Message: </p>
<textarea name="message" id="message-field" placeholder="Try adding text like https://google.com" style="width:200px;height:100px;"></textarea/>
<br/>
<button>submit</button>
</form>
This is only a front-end solution. Make sure you also have a check on the backend because javascript based validation can be easily bypassed.

Message length and filtering links still leave a number of options for spammers to breach your form.
You can quite easily implement a Google Recaptcha or implement your own in whatever backend language you're using.
The conditions you're looking for in your OP are,
if ($('#messag').html().length > 12)
if ($('#messag').html.indexOf('href') >= 0)
Cheers

Related

Integrating and validating invisible recaptcha

I want to add recaptcha to a form, I registered for it and got the keys.
<form>
<input type="text" name="name" />
<input type="email" name="email" />
<textarea name="message"></textarea>
<input type="submit" name="submit" value="Send" />
</form>
Then I added this code to the page:
<script src='https://www.google.com/recaptcha/api.js?render=My_Website_Key'></script>
Next I added this Javascript/Jquery code:
//When page is loaded.
$(document).ready(function() {
grecaptcha.ready(function() {
grecaptcha.execute('The Website Key', {action: 'homepage'}).then(function(token) {});
}); //Recaptcha ready
}); //Page is loaded
Finally I'm trying to verify, But there is no hidden element with a value to use or anything to send to the backend to check.
So how to check from the backend?
Take a look at:
https://developers.google.com/recaptcha/docs/invisible
You can link it to the submit button and link it to inputs fields

Unable to redirect to another URL through JS

So, I made a simple page where the submit button should redirect to another URL. Here's my code.
HTML:
<form onsubmit="javascript:redirectRoll();">
<input type="text" id="key" name="Roll" placeholder="Enter the full Roll No" size="60" pattern=".{10,}" required title="Every Roll No is exactly of 10 characters" maxlength="10" autofocus required><br></span></input><br>
<input type="submit" name="submit"></input>
</form>
JS
function redirectRoll(){
window.location.href="www.example.com";
}
Whenever I click on Submit it just takes me back to the same page. Help, please!
Ok, I'm posting the link to the website I've just hosted:
jbresults.site88.net/results.html
this should make it easy for you guys to find the problem :)
As #teemu has commented, the form submission is overriding the redirect. You need to use the following code for your redirectRoll function. Make sure to change the onsubmit value to "redirectRoll(event)"
function redirectRoll(e) {
e.preventDefault();
location.href = "example.com";
}
Just try this
function redirectRoll()
{
$(location).attr('href','www.example.com');
}
This work for me :
function redirectRoll(){
window.location ="www.example.com";
}
you may change the way you are calling the function
in the html
<form>
<input type="text" id="key" name="Roll" placeholder="Enter the full Roll No" size="60" pattern=".{10,}" required title="Every Roll No is exactly of 10 characters" maxlength="10" autofocus required><br></span></input><br>
<input type="submit" name="submit" onclick="redirectRoll();"></input>
</form>

validate form with ajax using POST with no jquery needed

I'm trying to validate a form without using jQuery as in my project I do not need jQuery. I would like to save on loading files for the sake of performance. I've checked on youmightnotneedjquery and I found this snippet to use POST with Ajax.
I only find tutorials how to validate emails with jQuery or PHP. Could somebody could explain me, guide me or knows about a tutorial that could help me?
I would appreciate it greatly!
I also checked this framework from microjs.com but there are also no instructions :(
Ajax:
var request = new XMLHttpRequest();
request.open('POST', '/my/url', true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
request.send(data);
HTML form:
<form class="contact-form">
<label for="email">
Email*
</label>
<input id="email" type="email" name="email" placeholder="example#emailserver.com" required>
<label for="telephone">
Telephone
</label>
<input id="telephone" type="tel" name="telephone" placeholder="+32 343 645 461">
<label for="message">
Message*
</label>
<textarea id="message" placeholder="Place your magnificent message here..." required></textarea>
<input id="sendcopy" type="checkbox" name="sendcopy">
<label for="sendcopy">
Send yourself a copy of the email
</label>
<input type="submit" name="submit" value="Send">
<span class="required-field-legend">
<!-- insert icon -->
Required fields
</span>
You can take a look at Mozilla Developer Network and try using XMLHttpRequest. To give you the basic idea, you will have to write a php file which receives the information from the form fields, does some checking and sends an XML response back. Then you will have to show something to the user according to what has happened (for example the email address was empty).
Another approach (which is the one I would suggest) is to do your validation with javascript. Just get the value of the element you want, for example:
var tel = document.getElementById('telephone').value;
and then check if it is ok. You can do that with Regular Expressions. In case there is something wrong, notify the user. This way you don't use the server at all. I hope I 've helped...
See this jsfiddle to understand what I mean by saying I prefer validation at client side.

How to receive form NAME with Ajax post?

In my site, I have different pages with different types of form. I want to submit all the forms to 'process.php' using Ajax and process data at 'process.php'. But, I am unable to catch the form name or form submit name at 'process.php' while posting data through Ajax.
Could anyone please tell me how could I know which form has been submitted from 'process.php'?
I tried the following steps that failed:
CHANGE PASSWORD.PHP
<form id="change_password_form" action="process.php" method="POST">
<input type="password" id="current_password" name="current_password" />
<input type="password" id="new_password" name="new_password" />
<input type="password" id="confirm_password" name="confirm_password" />
<input type="submit" value="change password" id="submit" name="change_password" />
</form>
AJAX.JS
$("#submit").click(function(e){
e.preventDefault();
$.ajax({
url:"process.php",
type:"POST",
data:$("#change_password_form").serialize(),
success: function(data){
$("#msg").html(data);
},
});
});
PROCESS.PHP
if(isset($_POST['change_password'])){
echo("<p>".$_POST['current_password']."</p>");
echo("<p>".$_POST['new_password']."</p>");
echo("<p>".$_POST['confirm_password']."</p>");
}
The above code does not echo anything because Ajax did not post INPUT >TYPE >SUBMIT .
Here is what it posted:
Array
(
[current_password] => 12345
[new_password] => 123
[confirm_password] => 12
)
How would I make Ajax post the input>type>submit ? or else, if I am posting multiple form data to same PHP file for processing, how would I make PHP understand which form has been submitted?
Your reply would be highly appreciated.
Did I detail too much? My apology is before you.
You can assign a name to each form.
For example, in the above form,
<form name="change_password_form" id="change_password_form" action="process.php" method="POST">
<input type="password" id="current_password" name="current_password" />
<input type="password" id="new_password" name="new_password" />
<input type="password" id="confirm_password" name="confirm_password" />
<input type="submit" value="change password" id="submit" name="change_password" />
</form>
Then in your javascript,
$("#submit").click(function(e){
e.preventDefault();
$.ajax({
url:"process.php",
type:"POST",
data:$("#change_password_form").serialize()+'&form_name='+$("#change_password_form").attr("name"),
success: function(data){
$("#msg").html(data);
},
});
});
And in your PHP file,
if(isset($_POST['form_name'])){
if($_POST['form_name']=="change_password_form")
{
echo("<p>".$_POST['current_password']."</p>");
echo("<p>".$_POST['new_password']."</p>");
echo("<p>".$_POST['confirm_password']."</p>");
}
//Similarly, add your other form processing code.
}
Note : You should never trust user input. $_POST elements can be easily manipulated. Always escape the input before inserting it into a database, or use PDO.
A good and more reliable way do pass extra info in a form is by using the hidden input type. If you add to your form something like
<input type="hidden" name="form_type" value="change_password" />
And change your PHP into
if(isset($_POST['form_type']) && $_POST['form_type'] == 'change_password')
Then you can get your data and any other information you might want to pass along with other hidden fields.
I would use a hidden field with desired name and that will be definitely posted and capture the same on PHP page and process my conditions.
It is easiest/quickest approach, I think.
I would use something like this:
url:"process.php?form=change_password",
Then in process you know which form was submitted with $_GET['form'];

how validate fields using jquery validation plugin

i am newbie in jquery. i searched in google and i got Validation Plugin. but it's not working. i have attached jquery.validate.js in my header part.
my code looks like...
<form action="" method="" id="contact">
<div class="form-group"">
<label> Your Name </label>
<input type="text" class="form-control" placeholder="Enter Your Name" id="firstname" required="" minlength="5"/>
</div>
<div class="form-group">
<label> Your E-mail </label>
<input type="email" class="form-control" placeholder="Enter Your Email" id="email"/>
</div>
<button type="submit" class="btn btn-primary btn-lg"> Send</button>
</form>
<script type="text/javascript">
$('#contact').validate({
success: function(label){
label.addClass("has-success").text("ok");
}
});
</script>
but it's not validating my field... Can anyone say how to use it? i know i am doing something wrong here but i am newbie so...
Did you include jquery-plugin validation.js file in your project directory?? If no then you need to include http://www.websitecodetutorials.com/code/jquery-plugins/validation.js
The submit button is essencial since it fires the validate function:
$("#myform").validate({
submitHandler: function(form) { // this line is important
form.submit(); // with this line the validate function gets fired
}
});
perhaps you should also try following:
– make sure your jquery library is correctly embedded in your document
– make sure your validation.js is in the correct folder
Try using document ready instruction:
$(function(){
$('#contact').validate();
});
it works: http://jsfiddle.net/RQMaV/15/

Categories