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.
Related
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
Please can someone help me with how to create an input field that would take text, pictures, gif, attachment etc. just like Facebook/twitter/Quora's "Create Post" input field... it would be good to see a plugin that can help with that or if I can create it myself! thanks in advance... I know what you are about to say, I did my research and I couldn't find anything that help me with building. I just want something like a 101 of such palette so that I can continue build it... I will also like to add my own conventions (like Ctrl + B to bold etc.)
Take a look at this.
"post" Sends the form-data as an HTTP post transaction. The HTML action attribute is used to specify where the form data is to be sent to the server after submission of the form. It can be used in the element.
URL: It is used to specify the URL of the document where the data to be sent after the submission of the form.
All you need now is to specify a textarea where that post will be sent and style the button to say "Post" instead of the regular "Submit".
<form action="/action_page.php" method="post">
<label for="fname">First name:</label>
<input type="text" id="fname" name="fname"><br><be>
<label for="lname">Last name:</label>
<input type="text" id="lname" name="lname"><br><be>
<input type="submit" value="Submit">
</form>
I have a JSON file and I want to change its properties through an HTML form:
<h1>product detail</h1>
<form>
Name:<br>
<input id="prod-name" type="text" name="name" readonly><br>
Number:<br>
<input id="prod-number" type="text" name="number" readonly>
<br>
<textarea id="prod-desc" name="description" cols="100" rows="10" readonly>description</textarea>
<br>
<textarea id="prod-img" name="images" cols="100" rows="10" readonly>images</textarea>
<br>
</form>
<button id="save-changes">SAVE</button>
I already retrieved the data from a JSON file with jQuery and AJAX but now I need to save it IN A FILE (not local storage)
$('#save-changes').on('click', function () {
json[index].name = $("#prod-name").val();
json[index].number = $("#prod-number").val();
json[index].description = $("#prod-desc").val();
});
So basically i want to change name, number and description in my JSON file
Ok so based on your comments:
I think there are two ways to go about it. One is editing a javascript object and sending it back to the server. The second (which I find more simple) is to simply send back the form as it is edited. Both would require the item has some sort of unique id which is not editable, so that you can keep track of what it is you are actually updating in the server database.
so just make the form functional (simplified example):
<form name="yourForm" method="POST" action="pageHandlingUpdateRequestOnServer">
<input name="db-item-id" type=hidden>
<input name="prod-name" type="text">
<input name="prod-number" type="integer">
<input name="prod-desc" type="textarea">
<input type="submit" value="Submit">
</form>
this form will fire a POST request to the address on action. That address should know how to handle a POST request, taking it, and updating your server database with it.
I don't know what you are using server-side. I also don't know what type of DB you run. if it's php look into PDO statements, and $_POST access. it's too long to answer here. But these two terms should lead you there with some effort and you'll learn a bunch of stuff during the process.
Some useful links:
< form > format
php $_POST
php form handling
php pdo statement
I currently have a working code that just allows users through once they click a button to accept terms. I would like to integrate a password field and accept button that would only allow someone through if the password is correct.
Here is my current working code with the simple button:
Agree to Connect:
<br>
<br>
<form method="post" id="login" action="http://10.0.0.1:5280/">
<input type="hidden" name="accept_terms" value="yes">
<input type="hidden" name="redirect" value="http://www.anderson1216.com/wifi-success.html">
<input type="hidden" name="mode_login">
<input type="submit" value="Accept Terms of Use and Connect">
</form>
<br>
//agreement text here
<br>
<br>
We thank you for your understanding and cooperation.
<br>
<br>
<form method="post" id="login" action="http://10.0.0.1:5280/">
<input type="hidden" name="accept_terms" value="yes">
<input type="hidden" name="redirect" value="http://www.anderson1216.com/wifi-success.html">
<input type="hidden" name="mode_login">
<input type="submit" value="Accept Terms of Use and Connect">
</form>
this is a simple password form that I found:
<head>
<script type="text/javascript">
function isValid(){
var password = document.getElementById('password').value;
if (password == "password123")
{alert('Correct!')
else
{alert('Wrong Password')}
}
</script>
</head>
<form name="PasswordField" action="">
Password:
<input type="password" id="password" name="password">
<input type="button" value="Log in" onclick="isValid();">
</form>
In order for the code to work, the first statement from the first block of code needs to be included somewhere to tell the router that the person accepted, then I want it to redirect to another website after they click the button. No alert is needed for a correct password, just the incorrect ones. Any suggestions?
I would SERIOUSLY advise not having the password listed in the js!! This is able to be seen by anyone looking at the source code. You need to implement a more secure password system with a hashed and salted password held in a secure database and checked via an AJAX call or PHP.
It looks like you are wanting to put this on a home router, possibly as a landing page? If you can elaborate a bit more I might be able to provide more help.
If you are trying to prevent someone from accessing the site unless they have know a secret password, then this is not the way to go about it. You would want to authenticate the user on the server side, not the client side, because anyone with limited knowledge of JavaScript can spoof authentication on the client side using the developer console.
If, however, you are just wanting to make certain that a human is agreeing to the terms of the agreement by entering in an arbitrary known password, then this method is fine.
I would agree with gavrig above to hash and salt them for safety.
But if i got your question right, here's a fiddle i put together to solve it. I've mixed jquery and javascript intentionally.
Agree to Connect:
<br>
<br>
//agreement text here
<br>
<br>
We thank you for your understanding and cooperation.
<br>
<br>
<form method="post" id="login" action="http://10.0.0.1:5280/">
<input type="password" id="password" name="password">
<input type="hidden" name="accept_terms" value="yes">
<input type="hidden" name="redirect" value="http://www.anderson1216.com/wifi-success.html">
<input type="hidden" name="mode_login">
<input type="submit" value="Accept Terms of Use and Connect">
</form>
$('form').on('submit', function(e){
e.preventDefault();
var password = document.getElementById('password').value;
if (password == "password123")
{
this.submit();
}
else
{
alert('Wrong Password');
}
});
https://jsfiddle.net/tL7qcc5n/2/
NoCatSplash does not support authentication. Any user could simply bypass your authentication by manually posting to http://10.0.0.1:5280/
If you are serious about authentication, you should use another method, such as using a Radius server. This could even be installed on the router itself, given that it has good enough hardware to support it.
Hi I'm trying to login a user to Box.com from a webpage. I accomplished the first part with a simple HTML form submit:
<form action="https://www.box.com/api/oauth2/authorize" type="POST" enctype="application/x-www-form-urlencoded">
<input type="text" name="response_type" value="code">
<input type="text" name="client_id" value="[REMOVED]">
<input type="text" name="state" value="vexhax97td8xf_SomeTemporaryValueForTesting">
<input type="submit">
</form>
This works fine, and I get the authorization code from the query parameters using javascript. I then try the same thing to get the access code (the auth-code is set by javascript on page load):
<form action="https://app.box.com/api/oauth2/token" type="POST" enctype="application/x-www-form-urlencoded">
<input type="text" name="grant_type" value="authorization_code">
<input id="auth-code" type="text" name="code" value="">
<input type="text" name="client_id" value="[REMOVED]">
<input type="text" name="client_secret" value="[REMOVED]">
<input type="submit">
</form>
But I get an "Invalid grant_type parameter or parameter missing" error. Plus this wouldn't be a good user experience to show the response json anyway. I've tried it without the enctype="application/x-www-form-urlencoded" and get the same error.
The Box tutorial does it with curl which obviously isn't an option on a webpage. How do I get the access token without hitting the "Invalid..." error and is there a way to do this via javascript behind the scenes?
For the authorization-code to access-token exchange, "redirect_uri" parameter is missing. But this is not the real problem.
The exchange is supposed to take place on the server-side and you are doing it on the client-side (browser). Maybe you could do the exchange by AJAX call to correctly handle JSON reply but only if box.com allows CORS (which I doubt).
This way you would also expose your client_id and client_secret on your web page (so why do you hesitate posting it on the stackoverflow?).