Check $_POST data with jquery before submitting the form - javascript

I have a form that sends the store the First Name of the user in a database. I was checking the information send by the user using regex in php.
To make my project more interactive, I decided to validate the information jQuery before sending it to PHP.
My Project looks like this:
<script type="text/javascript" src="jquery-2.2.3.min.js"></script>
<script src="http://code.jquery.com/ui/1.9.1/jquery-ui.js" type="text/javascript"></script>
<body>
<form >
<div>
<label>First Name</label>
<input name="firstname" type="text">
</div>
<div>
<input type="submit">
</div>
</form>
</body>
</html>
<script>
$(document).ready(function() {
$("form").submit(function (e) {
var firstname = $(this).find('input[name="firstname"]').val();
var regex = /^[A-Za-z0-9 \-']+$/;//Only numbers, Letters, dashes, apostrophes and spaces are accepted
if(regex.test(firstname)){
alert('Valid Name.');
}else{
alert('Invalid Name.');
e.PreventDefault();
}
});
});
</script>
Now I have 2 questions:
Is it really need to check the First Name in PHP again before storing the data in the database ? (To improve security)
How can I submit the form right after the alert('Valid Name.'); ?
Thanks for providing your help.

First of all have in mind that the validation of users input is implementing at the server side of an application only!!! You can not validate input data at client side with JS because it can be passed very easy(either by disabling javascript or by using tools like Curl).
However you can increase user experience like validate an input before submitting the form or inform the user that forgot to fill in an input.
To inform the user about a not fill in input you can just use the new html 5 attribute required like above
Username: <input type="text" name="usrname" required>
the required attribute will not let the user submit the form unless he had filled the associated input.
Also you can use the maxlength attribute to address a use case like "A password must have X max letters.
Password: <input type="password" name="pass" maxlength="8" size="8"><br>
How to validate input at server side
There are many techniques for this and you can find all of them here at Stackoverflow. Ι will refer the top voted post How can I prevent SQL injection in PHP? which answer exactly your question.
Just two bullets that compact the above post that i suggest you read otherwise
Always escape your data
Use mysqli instead of mysql
How can I submit the form right after the alert('Valid Name.'); ?
this is very easy just use this code
<form action="action_page.php" method="post">
<div>
<label>First Name</label>
<input name="firstname" type="text">
</div>
<div>
<input type="submit">
</div>
</form>
the above code will "send" user's input for process at action_page.php using POST method, where you can read using $_POST supergloba table like $firstname = $_POST['fistsname'] etc.

TRY This
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.15.0/jquery.validate.js" ></script>
<script type="text/javascript" src="jquery-2.2.3.min.js"></script>
<script src="http://code.jquery.com/ui/1.9.1/jquery-ui.js" type="text/javascript"></script>
<body>
<form >
<div>
<label>First Name</label>
<input name="firstname" id="first_name" type="text">
</div>
<div>
<input type="submit">
</div>
</form>
</body>
</html>
<script>
jQuery.validator.addMethod("firstName",function(value,element,param)
{
if(this.optional(element))
{//This is not a 'required' element and the input is empty
return true;
}
if(/^[A-Za-z0-9 \-']+$/.test(value))
{
return true;
}
return false;
},"Please enter a valid First Name");
$(function()
{
$('#myform').validate(
{
rules:
{
first_name:{ required:true, firstName:true }
}
});
});
</script>

Firstly you should ALWAYS validate server side for form submission, especially if you are passing those value along to a DB - SQL injection, the struggle is real.
As for the form submission flow you can...
return true
... after the valid name alert and the form to submit as it normally would.
Since you already have bound to that submit event, It would be even better for the user if you submitted the form via ajax, and providing feedback if the server validation fails. Thus the user never leaves the page and you are able to handle both client and server validation.
Take a look at ParsleyJS - http://parsleyjs.org/ - w00t!

Related

prevent blank form submission

If I want to prevent my form to be submitted if the fields are blank and highlight the blank fields.The code I have so far works if I try to submit when it is blank but doesnt submit if the fields are filled. I cannot seem to figure out what I am doing wrong. Please help
JavaScript code:
function CheckFields(){
if((document.getElementById('title').value=="") || (document.getElementById("textfield").value=="")){
const element = document.querySelector('form');
element.addEventListener('submit',event =>{
event.preventDefault();
alert("Fill the form to be submitted");
document.getElementById("title").style.backgroundColor=red;
document.getElementById("title").style.backgroundColor=red;
});
}
HTML:
<input name="post" type="submit" value="Post" onclick="CheckFields();">
Re-posted from: https://developer.mozilla.org/en-US/docs/Learn/Forms/Form_validation for the purposes of having the a static answer to this question, as the webpage may change
Using built-in form validation
One of the most significant features of HTML5 form controls is the ability to validate most user data without relying on JavaScript. This is done by using validation attributes on form elements. We've seen many of these earlier in the course, but to recap:
required: Specifies whether a form field needs to be filled in before the form can be submitted.
minlength and maxlength: Specifies the minimum and maximum length of textual data (strings)
min and max: Specifies the minimum and maximum values of numerical input types
type: Specifies whether the data needs to be a number, an email address, or some other specific preset type.
pattern: Specifies a regular expression that defines a pattern the entered data needs to follow.
In general that is a wrong way to validate fields, but anyhow your error is the order of the condition and form submit event. So it should be like this:
var myForm = document.querySelector('form');
var myTitle = document.getElementById('title');
var myTextfield = document.getElementById('textfield');
myForm.addEventListener('submit', event=>{
if(myTitle.value=="" || myTextfield.value==""){
alert("Fill the form to be submitted");
myTitle.style.backgroundColor=red;
myTextfield.style.backgroundColor=red;
return false;
} else {
return true;
};
});
You can add required to input fields for client-side validation. For more advanced validation, you may want to add server-side validation via a model.
See required in action:
<form action="/action_page.php">
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname" value="" required><br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname" value="Doe"><br><br>
<input type="submit" value="Submit">
</form>
You can validate a form in many ways. In Html 5 form you can add required for client side validation. You can also validate form from server side. And you can also use ajax for realtime form validation. Use focus on the field.. to highlight a field that is not filled.

Creating URL from form fields in javascript

So, i'm really new to HTML and javascript, and I want to take values from a form and process them with a script. I have a couple of fields including username, password, and two confirm password fields in HTML. With javascript I want to collect the username, and check if the password field is filled out. If it is, I want to make var ispass equal to 'yespass' or 'nopass'. When I submit the form, I want to go the url http://www.example.com?un=username&pass=yespass (or nopass).
Javascript:
<script language="javascript" type="text/javascript">
function processFormData(){
var user = document.getElementById('username').value;
var pass = document.getElementById('password').value;
var ispass;
if (pass.length > 0){
ispass = "yespass";
}else{
ispass = "nopass";
}
return "http://www.example.com?un=" + user + "&pw=" + ispass;
</script>
HTML:
<form onsubmit="window.location.href=processFormData();">
Please enter your current e-mail address and password below.<br><br>
<input type="text" id="username" placeholder="E-mail Address"><br><br>
<input type="password" id="oldpassword" placeholder="Old Password"><br><br><br>
Please type your new password below:<br><br>
<input type="password" id="newpassword1" placeholder="New Password"><br><br>
<input type="password" id="newpassword2" placeholder="Confirm New Password"><br><br>
<input type="submit" id="gobutton" value="Reset Password"/>
</form>
I cannot figure out a proper way to do this, because this does not seem to be working at all. Any suggestions or recommendations?
You could pull this off with a hidden form field and an onchange event:
<input type="hidden" id="ispass" value="no" onchange="checkPass(this);" />
This input would go in your form. Then on your password field, add an onchange handler:
function checkPass(input) {
document.getElementById("ispass").value = "yes"
};
Also, if you set the method on your form, submitting the form can generate the url based on the form inputs:
<form method='get' action='...' />
Here's a jsfiddle that demonstrates the result.
Also, if you're new to javascript, you may want to look into a library like jQuery to simplify some of your interaction with the page. It's really easy to learn, and there's a great community around it to help with any problems you might run into.
HTH,
Aaron

Form gets submitted despite of invalid inputs

I wrote an HTML code in which i'm validating the text field for alphabetical value Regex=/^[a-zA-Z]*$/. Actually for invalid input I want that form should not get submitted.
Validation Code
function Validate() {
var fname=$("#fname").val();
if(!(fname.match(Regex)))
alert("Invalid First Name");
return false;
}
HTML Code
<input type="text" name="fname" id="fname" onblur="return Validate();"/>
What should I do, so that for invalid value form should not get submitted.
It looks like you have to return false in onsubmit handler. onblur just handles focus.
Try to change onblur -> onsubmit
Use the onsubmit event of the form element to return true when validation was ok or false if any field did not validate.
Here is a working example. It also demonstrates that you should not rely on client sided validation since nobody stops you from doing the get (or even post) request anyway by just typing in the url. You have been warned about the limitations of client sided validation so here is the code:
<html>
<head>
<script>
function Validate() {
var text = document.getElementById("fname").value;
// simple validation example
if (text != "secret") {
alert("you must enter the right secret string!");
return false;
}
// everything validated
return true;
}
</script>
</head>
<body>
<form name="myForm" method="get" onsubmit="return Validate();">
<input type="text" name="fname" id="fname"/>
</form>
</body>
</html>

On form submit, mailto from javascript with form values

I have a form, and when the form is submitted (input type="submit"), i would like to open the clients default mail-browser with a pre-populated email-message.
So when the user clicks submit two things need to happen. Open email and submit form.
Also, how can i use the values entered in the form to prepopulate the email?
I'm new to javascript-jquery so please, any code example would be of great help!
Thanks for your help!
Before submitting the form you could do:
window.location.href = 'mailto:nicola#mio.it';
this will open the predefined mail client and you can also prefill some field. look at the mailto sintax here or post some more info so that we can help you;
This could be done like this :
$('input[type=submit]').click(function(){
window.location.href = "mailto:" + $('#email').val();
});
I have used a code like this when I needed to send via mailto using my local email client, it may help:
<html>
<head>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<form id="myform" enctype="text/plain" action="test.php" method="post" >
<input type="text" value="value1" id ="field1" name="field1">
<input type="checkbox" value="valuel2" id ="field2" name="field2" checked>
<input type="checkbox" value="value3" id ="field3" name="field3" >
<textarea id="myText" name ="texty">
Lorem ipsum...
</textarea>
<button onclick="sendMail(); return false">Send</button>
</form>
<script>
function sendMail() {
$myform = $('#myform');
$myform.prop ('action','mailto:mymail#mydomain.es');
$myform.submit();
}
</script>
</body>
</html>
you can prepopulate form with
$("textarea").val('Your message here! You\' have to strip \'');
if it's default email clien't, I'm afraid it's not possible

Change post form

I have simple login form in my website. In given requirements stands, that password mustn't been sent to server, but only MD5 hash. I took simple MD5 function and now, when with onClick on submit button I change hidden text from password to md5(password). This works fine, but user sees, that something with his password is happening. I would like to make it transparent and change this particular part of form dynamically with onPost (or smth like this) callback.
I can't find any tutorials how to deal with manipulating POST table/form in javascript (jquery?) so if anyone could help I would appreciate.
As far as I know input fields that don't have name don't get submitted to the server. So you could have a hidden field and in the onsubmit event of the form copy the value of the password field into the hidden field by applying the MD5 checksum:
<form method="post" action="/login">
<input type="password" id="password" />
<input type="hidden" name="password" id="hiddenpassword" />
<input type="submit" value="Login" />
</form>
and then:
$('form').submit(function() {
var password = $('#password').val();
var md5 = MD5(password);
$('#hiddenpassword').val(md5);
return true;
});

Categories