I have been working on creating a form with a set of fields like username, passwords etc....
I want to make validation when the SUBMIT button is clicked.
I'm trying to get alert from my border color. All fields are valid my border must change into Green color If it has any errors it should change to red color.
Any one has any ideas regarding to my problem
If anyone has any suggestion??
You can use jquery plugin.... here you are. JQuery Form validation custom example
Use jQuery validation plugin: http://docs.jquery.com/Plugins/Validation
In this plugin, you have to define validation rules for the field. You can also set the error messages for given field for given validation rule.
This plugin adds classes to valid and invalid field.
You have to give the css for that class.
For example:
$(document).ready(function(){
$(".my_form").validate({
rules:{ // validation rules
email_address: {
required:true,
email: true
},
password:{
minlength: 6
},
confirm_password: {
equalTo:"#password"
}
},
messages: {
email_address: {
required: "Please enter email address",
email: "Please enter valid email address",
},
/*
likewise you can define messages for different field
for different rule.
*/
}
errorClass: "signup_error",
/*This is error class that will be applied to
invalid element. Use this class to style border.
You can give any class name.*/
});
});
Once you click on submit button, and field is invalid, the plugin adds class to the element that you have specified as errorClass, and when you enter valid value in the field, the plugin will remove this class and will add 'valid' class by default.
You can use these two classes to style valid and invalid element using simple element.
.valid {
border-color:"green"
}
.signup_error {
border-color:"red"
}
Hope this resolves your problem.
Js i the way to go. You can find some really good validators for jQuery should you google for it.
To custom build a simple validator I would go like this
<form class="validator">
<input type="text" name="my-input-1" data-validator="integer"/>
<input type="text" name="my-input-2" data-validator="email"/>
....
</form>
<script>
$("form.validator").submit(evt, function() {
var errors = 0;
$(this).find('[data-validator]').each(function(e, i) {
var value = $(this).value;
switch($(this).data('validator')) {
case 'integer':
if (!(parseFloat(value) == parseInt(value)) && !isNaN(value)) {
$(this).css({'border-color': '#FF0000'});
errors++;
} else
$(this).css({'border-color': '#000000'});
break;
case 'email':
if (..... // regex validate email ...) {
$(this).css({'border-color': '#FF0000'});
errors++;
} else
$(this).css({'border-color': '#000000'});
break;
}
});
if (errors > 0) {
// If you want to prevent default event execution no matter what
evt.preventDefault();
// If you want you other attached events to NOT run
evt.stopPropagation();
// signal failure
return false;
}
// All is well, go on
return true;
});
</script>
of course it's always good practice to build functions for every validator and even better to wrap the whole thing in a jQuery widget (I would suggest using jQuery Widget Factory) which would allow you to enhance it in the future and keep you flexible to changes
You can use DOJO library to validate form fields. It's easy to implement.
Given below is the tutorial to implement dojo
http://dojotoolkit.org/documentation/tutorials/1.6/validation/
and this is the working example you can see...
http://dojotoolkit.org/documentation/tutorials/1.6/validation/demo/dijitcheck.html
I made a validation library just for general javascript purposes. It is even unit tested! You can override whatever you want fairly easily as well: https://github.com/parris/iz
As far as highlighting invalid fields you can just change the style of that field or add a class. The example below just changes the background color of the input and adds a message.
Working example: http://jsfiddle.net/soparrissays/4BrNu/1/
$(function() {
var message = $("#message"),
field = $("#field");
$("#the-form").submit(function(event) {
if (iz(field.val()).alphaNumeric().not().email().valid){
message.text("Yay! AlphaNumeric and not an email address");
field.attr("style","background:green;");
} else {
message.text("OH no :(, it must be alphanumeric and not an email address");
field.attr("style","background:red;");
}
return false;
});
});
The validator is called iz. It simply lets you chain validations together and it will tell you if everything passed or if you check the "errors" object it'll give you more specifics. Beyond that you can specify your own error messages. Check the docs on github.
What is happening here is we are setting a click handler for the submit event once the page is ready. return false; at the bottom of the submit callback prevents the form from submitting. If you return true; the form will continue on. Instead of return false you could also event.preventDefault(); but I prefer the return syntax for consistency. In the real world with multiple form elements you may do something like this (psuedo code):
var passed = true;
if (check field 1 is false)
...
if (check field 2 is false)
...
if (check field n is false)
passed = false
style and add message
if passed
return true
else
return false
The if statement checks the validation rules and makes changes to the DOM accordingly. By doing it in this way you are able to give a complete list of all passed and failed fields with a full description of what is incorrect.
I have used this plugin in the past, makes implementation very easy and has good documentation and examples.
My advice use jQuery
to try first create multiple inputs and give them a class
html:
<input type="text" class="validate" value="asdf" />
<input type="text" class="validate" value="1234" />
<input type="text" class="validate" value="asd123" />
<input type="text" class="validate" value="£#$&" />
<input type="text" class="validate" value=" " />
then use the code below to see how it works
jQuery:
// Validate Function
function validate(element) {
var obj = $(element);
if (obj.val().trim() != "") {
// Not empty
if (!/^[a-zA-Z0-9_ ]{1,10}$/.test(obj.val())) {
// Invalid
obj.css('border-color', '#FAC3C3');
if (!obj.next().hasClass('error'))
{ obj.after('<span class="error">Please use letters or numbers only and not more than 10 characters!</span>'); }
else
{ obj.next().text('Please use letters or numbers only and not more than 10 characters!'); }
} else {
// Valid
obj.css('border-color', 'lightgreen');
if (obj.next().hasClass('error'))
{ obj.next().remove(); }
}
} else {
// Empty
obj.css('border-color', '#FAC3C3');
if (obj.next().hasClass('error'))
{ obj.next().text('This field cannot be empty!'); }
else
{ obj.after('<span class="error error-keyup-1">This field cannot be empty!</span>'); }
}
}
$(document).ready(function() {
// Each
$('.validate').each(function() {
// Validate
validate(this);
// Key up
$(this).keyup(function() {
// Validate
validate(this);
});
});
});
jsfiddle : http://jsfiddle.net/BerkerYuceer/nh2Ja/
A server side validation example of your need. You may try it out.
<?php
error_reporting(0);
$green = "border: 3px solid green";
$red="border: 3px solid red";
$nothing="";
$color = array ("text1"=>$nothing , "text2"=>$nothing) ;
if ( $_POST['submit'] ) {
if($_POST['text1']) {
$color['text1'] = $green;
}
else $color['text1'] = $red;
if($_POST['text2'] ) {
$color['text2'] = $green;
}
else $color['text2'] = $red;
}
?>
<form method="post">
<input type="text" name="text1" style="<?php echo $color ['text1']?>" value="<?php echo $_POST['text1']?>">
<input type="text" name="text2" style="<?php echo $color ['text2']?>" value="<?php echo $_POST['text2']?>">
<input type="submit" name="submit">
</form>
Note
Always sanitize user input.
error_reporting off is not a good practice at all. I did it as this is not a code of production environment.
Check before trying to access in the post array using isset or something similar function like this.
Always check if a variable exist before using.
$("#btn").click(function(){
// Check all of them
if( $.trim($("#file").val()) == ""){
$("#file").css("border","1px solid #ff5555");
}else{
$("#file").css("border","1px solid #cccccc");
if( $.trim($("#showboxResimBaslik").val()) == ""){
$("#showboxResimBaslik").css("border","1px solid #ff5555");
}else{
$("#showboxResimBaslik").css("border","1px solid #cccccc");
if( $.trim($("#showboxResimEtiket").val()) == ""){
$("#showboxResimEtiket").css("border","1px solid #ff5555");
}else{
if($.trim($("#showboxResimSehir").val()) == ""){
$("#showboxResimSehir").css("border","1px solid #ff5555");
}else{
$("#showboxResimSehir").css("border","1px solid #cccccc");
$("#resimYukleForm").removeAttr("onSubmit");
$('#resimYukleForm').bind('submit', form_submit);
}
}
}
}
});
probably the easiest way is to use this javascript:
http://livevalidation.com/examples#exampleComposite
I think it suits your description the best.
check below link, here i have only checked for empty fields and if the fields are empty then changed input fields id which will change input field border color.
http://jsfiddle.net/techprasad/jBG7L/2/
I have used
$("#myb").click(function(){
that is on button click event but you can use submit event.
Here is what I would say is short precise and concise way to do this in jQuery.
HTML:
<form id="myform" name="form" action="http://www.google.com">
<div class="line"><label>Your Username</label><input class="req" type="text" /></div>
<div class="line"><label>Your Password</label><input class="req" type="password" /></div>
<div class="line"><label>Your Website</label><input class="req" type="text" /></div>
<div class="line"><label>Your Message</label><textarea class="req"></textarea></div>
<div class="line"><input type="submit" id="sub"></submit>
</form>
CSS:
.line{padding-top:10px;}
.inline input{padding-left: 20px;}
label{float:left;width:120px;}
jQuery:
$(function() {
function validateform() {
var valid = true;
$(".req").css("border","1px solid green");
$(".req").each(function() {
if($(this).val() == "" || $(this).val().replace(/\s/g, '').length == 0) {
$(this).css("border","1px solid red");
valid = false;
}
});
return valid;
}
$("#sub").click(function() {
$('#myform').submit(validateform);
$('#myform').submit();
});
});
LIVE DEMO
Well hi, you can use html5 "required" and "pattern" in your form's fields.
You'll get red border if it's wrong and green if it's right.
You can even style the :valid and :invalid entry fields if the colors aren't which you wanted.
I've never tested it but why not, it's better than nothing ;)
html5 solution
Firs Learn javascript, if you have some basic knowledge of js and need to know the logic, go on read..
First you need an event handler to run a function on form submit
Easiest way is (though there are better ways)
<form action="som.php" onsubmit="functionName()">
form here
</form>
This will trigger the function called functionname.
In function name function access the input fields and validate using regular expressions
function functionName()
{
//verification code
if(verified)
{
//code to change border to green
}
}
You need to get the input fields and validate them. If you don't know how to do that, get a few Javascript books
If you need to validate as soon as value is typed use the on onchange event on input fields
Related
I need the name and value of a button (Not an input type = submit) when a form is submitted with the button of type submit.
I know everyone always asks why, even though the "why" is not a part of the answer to the question so I will answer the why to save time. I want a form to direct a person to choose to login, register or submit email verification. So having buttons that I can set the label for, with each have a unique value for a given name would solve this need but the name and values are not included in the POST with the rest of the input data when BUTTON type = submit is used.
Given the information in HTML5 Spec as shown on this site https://www.htmlquick.com/reference/tags/button-submit.html it seems like it's supposed to work. But short of adding javascript to manually add the key value pair to the post on click it doesn't seem to work.
Now, I want to ask why? If only inputs can be added to the data list then why isn't there an option to change the label of the submit inputs?
*EDIT
So far everyone agrees that what I've done should work, so lets get to the specific case and see if we can find where the problem is then.
Using this form:
<form data-targetblock="accountBlock" class="fetchForm" action="<?=ADDRESS ?>/MAINhubs/accountBlockHub.php" method="post">
<fieldset>
<legend>Member Login</legend>
<input type="hidden" name="formTarget1" value="test">
<button type="submit" name="formTarget" value="login">Log In</button>
<button type="submit" name="formTarget" value="register">Register</button>
<button type="submit" name="formTarget" value="verify">Verify Your Email</button>
</fieldset>
</form>
Sent with this:
function addFetch(event, targetBlock, domain)
{
event.preventDefault();
const form = new FormData(event.target);
const request = new Request(event.target.action,
{
method: event.target.method,
body: form,
mode: 'same-origin',
credentials: 'same-origin'
});
fetch(request)
.then(response => {
if(response.ok)
{
return response.text();
}
else
{
document.getElementById(targetBlock).innerHTML = 'ERROR! ERROR! There has been an ERROR!'
}
})
.then(function(text){document.getElementById(targetBlock).innerHTML = text;})
.catch(error => console.log('There was an error:', error))
}
Going to this:
<?php
session_start();
if ($_SERVER['REQUEST_METHOD'] === "POST")
{
var_dump($_POST);
}
?>
Gets me this when I click Log In:
formTarget1 = test
I'm gonna guess it has to do with this line in the Fetch:
const form = new FormData(event.target);
To answer the question of how the function is called, this JS is run to add the function to all applicable forms:
function fetchFormCallback(mutations)
{
mutations.forEach(function(mutation)
{
for (const thisForm of Array.from(document.getElementsByClassName('fetchForm')))
{
addFormListener(thisForm, thisForm.dataset.targetblock)
}
});
}
function generalCallback(mutations)
{
mutations.forEach(function(mutation)
{
// Take alertBlocks and move them to bottom of ID outerFrame because of IOS bug
if (newAlertBlock = document.getElementById('alertMessageBlock'))
{
if (newAlertBlock.dataset.relocated !== 'true')
{
var destinationBlock = document.getElementById('outerFrame');
destinationBlock.appendChild(newAlertBlock);
newAlertBlock.dataset.relocated = 'true';
}
}
// Get getElementsByClassName closeButton
for (var closeButton of Array.from(document.getElementsByClassName('closeButton')))
{
if (closeButton.dataset.closeButton !== 'true')
{
closeButton.dataset.closeButton = 'true';
closeButton.addEventListener('click', function(){this.parentNode.parentNode.removeChild(this.parentNode);});
}
}
// Potentially auto close based on a closeButton class of AUTO
});
}
document.addEventListener("DOMContentLoaded", function()
{
var config = {childList: true};
for (const thisForm of Array.from(document.getElementsByClassName('fetchForm')))
{ // setup all fetchforms
addFormListener(thisForm, thisForm.dataset.targetblock);
var thisTargetBlock = document.getElementById(thisForm.dataset.targetblock);
// if notset dataset.mutationobserver OR
if (thisTargetBlock.dataset.mutationobserver !== 'true')
{
thisTargetBlock.dataset.mutationobserver = 'true';
var observer = new MutationObserver(fetchFormCallback);
observer.observe(thisTargetBlock, config);
}
}
config = {childList: true, subtree: true};
var generalObserver = new MutationObserver(generalCallback);
generalObserver.observe(document, config);
});
function addFormListener(form, targetBlock)
{ // first check if element has attribute set for eventListeners
if (form.dataset.submitlistener !== 'true')
{
form.dataset.submitlistener = 'true';
form.addEventListener('submit', function()
{
addFetch(event, targetBlock);
});
}
}
EDIT:
We've confirmed that the issue here is that FormData is for some reason not supposed to include the submit value. Why a value should be excluded just because it may not be present/needed in the use case is beyond me. I do have a reason why it should be included and have documented it above. I developed this structure to be as universally applicable as possible without the addition of code for special case uses.
So now my evolving question has become this:
How; using the above functions, can I get the value of the clicked submit button, and include that name value pair in the FormData without changing the fundamental structure of these functions that otherwise do exactly what I want them to do in every other case.
This discussion illustrates that it's possible but has been reworked based on the spec to no longer do exactly what I'm trying to do:
FormData() object does not add submit-type inputs from form, while on Firefox
If I can't access the name and value of the button at the point of submition, then I might as well make another eventlistener to all BUTTON elements in forms that adds a hidden input with it's values on click... Before I go and do that, I can already see hurdles like the event.preventDefault(); line in the addFetch function might prevent the on click from happening? I guess it's back to trial and error unless someone has a better thought.
In your PHP:
$_POST['formTarget'];
Will have the value of the submit button. Either login, register, etc.
However I would not use a form for this, there is no need. I would just simply use links and style them as buttons if you wanted them to look like a button.
Edit: Based on your additions to the post. I offer an alternative way to accomplish this using data attributes.
HTML:
<fieldset>
<legend>Member Login</legend>
<button id="loginButton" data-url="getForm.php" data-target-block="#showForm" data-form-type="login">Log In</button>
<button id="registerButton" data-url="getForm.php" data-target-block="#showForm" data-form-type="register">Register</button>
<button id="verifyButton" data-url="getForm.php" data-target-block="#showForm" data-form-type="verify">Verify Your Email</button>
</fieldset>
<div id="showForm"></div>
<script>
document.querySelector("#loginButton").addEventListener("click", addFetch);
document.querySelector("#registerButton").addEventListener("click", addFetch);
document.querySelector("#verifyButton").addEventListener("click", addFetch);
function addFetch() {
const data = new FormData;
const targetBlock = this.dataset.targetBlock;
for(element in this.dataset) {
data.append(element, this.dataset[element]);
}
const request = new Request(this.dataset.url,
{
method: "POST",
body: data,
mode: 'same-origin',
credentials: 'same-origin',
});
fetch(request).then(response => {
if(response.ok) {
return response.text();
} else {
document.querySelector(targetBlock).innerHTML = 'ERROR! ERROR! There has been an ERROR!'
}
}).then(function(text){document.querySelector(targetBlock).innerHTML = text;})
.catch(error => console.log('There was an error:', error))
}
</script>
PHP:
<?php
if ($_SERVER['REQUEST_METHOD'] === "POST") {
switch($_POST['formType']) {
case 'verify':
echo "verify Form";
break;
case 'register':
echo "Register Form";
break;
case 'login':
echo "Login Form";
break;
default:
echo "Not valid";
break;
}
}
Sometimes when the response is slow, one might click the submit button multiple times.
How to prevent this from happening?
Use unobtrusive javascript to disable the submit event on the form after it has already been submitted. Here is an example using jQuery.
EDIT: Fixed issue with submitting a form without clicking the submit button. Thanks, ichiban.
$("body").on("submit", "form", function() {
$(this).submit(function() {
return false;
});
return true;
});
I tried vanstee's solution along with asp mvc 3 unobtrusive validation, and if client validation fails, code is still run, and form submit is disabled for good. I'm not able to resubmit after correcting fields. (see bjan's comment)
So I modified vanstee's script like this:
$("form").submit(function () {
if ($(this).valid()) {
$(this).submit(function () {
return false;
});
return true;
}
else {
return false;
}
});
Client side form submission control can be achieved quite elegantly by having the onsubmit handler hide the submit button and replace it with a loading animation. That way the user gets immediate visual feedback in the same spot where his action (the click) happened. At the same time you prevent the form from being submitted another time.
If you submit the form via XHR keep in mind that you also have to handle submission errors, for example a timeout. You would have to display the submit button again because the user needs to resubmit the form.
On another note, llimllib brings up a very valid point. All form validation must happen server side. This includes multiple submission checks. Never trust the client! This is not only a case if javascript is disabled. You must keep in mind that all client side code can be modified. It is somewhat difficult to imagine but the html/javascript talking to your server is not necessarily the html/javascript you have written.
As llimllib suggests, generate the form with an identifier that is unique for that form and put it in a hidden input field. Store that identifier. When receiving form data only process it when the identifier matches. (Also linking the identifier to the users session and match that, as well, for extra security.) After the data processing delete the identifier.
Of course, once in a while, you'd need to clean up the identifiers for which never any form data was submitted. But most probably your website already employs some sort of "garbage collection" mechanism.
Here's simple way to do that:
<form onsubmit="return checkBeforeSubmit()">
some input:<input type="text">
<input type="submit" value="submit" />
</form>
<script type="text/javascript">
var wasSubmitted = false;
function checkBeforeSubmit(){
if(!wasSubmitted) {
wasSubmitted = true;
return wasSubmitted;
}
return false;
}
</script>
<form onsubmit="if(submitted) return false; submitted = true; return true">
The most simple answer to this question as asked: "Sometimes when the response is slow, one might click the submit button multiple times. How to prevent this from happening?"
Just Disable the form submit button, like below code.
<form ... onsubmit="buttonName.disabled=true; return true;">
<input type="submit" name="buttonName" value="Submit">
</form>
It will disable the submit button, on first click for submitting. Also if you have some validation rules, then it will works fine. Hope it will help.
Create a unique identifier (for example, you can hash the current time), and make it a hidden input on the form. On the server side, check the unique identifier of each form submission; if you've already received that hash then you've got a repeat submission. The only way for the user to re-submit is to reload the form page.
edit: relying on javascript is not a good idea, so you all can keep upvoting those ideas but some users won't have it enabled. The correct answer is to not trust user input on the server side.
Disable the submit button soon after a click. Make sure you handle validations properly. Also keep an intermediate page for all processing or DB operations and then redirect to next page. THis makes sure that Refreshing the second page does not do another processing.
You could also display a progress bar or a spinner to indicate that the form is processing.
Using JQuery you can do:
$('input:submit').click( function() { this.disabled = true } );
&
$('input:submit').keypress( function(e) {
if (e.which == 13) {
this.disabled = true
}
}
);
I know you tagged your question with 'javascript' but here's a solution that do not depends on javascript at all:
It's a webapp pattern named PRG, and here's a good article that describes it
You can prevent multiple submit simply with :
var Workin = false;
$('form').submit(function()
{
if(Workin) return false;
Workin =true;
// codes here.
// Once you finish turn the Workin variable into false
// to enable the submit event again
Workin = false;
});
On the client side, you should disable the submit button once the form is submitted with javascript code like as the method provided by #vanstee and #chaos.
But there is a problem for network lag or javascript-disabled situation where you shouldn't rely on the JS to prevent this from happening.
So, on the server-side, you should check the repeated submission from the same clients and omit the repeated one which seems a false attempt from the user.
You can try safeform jquery plugin.
$('#example').safeform({
timeout: 5000, // disable form on 5 sec. after submit
submit: function(event) {
// put here validation and ajax stuff...
// no need to wait for timeout, re-enable the form ASAP
$(this).safeform('complete');
return false;
}
})
The simpliest and elegant solution for me:
function checkForm(form) // Submit button clicked
{
form.myButton.disabled = true;
form.myButton.value = "Please wait...";
return true;
}
<form method="POST" action="..." onsubmit="return checkForm(this);">
...
<input type="submit" name="myButton" value="Submit">
</form>
Link for more...
Use this code in your form.it will handle multiple clicks.
<script type="text/javascript">
$(document).ready(function() {
$("form").submit(function() {
$(this).submit(function() {
return false;
});
return true;
});
});
</script>
it will work for sure.
This allow submit every 2 seconds. In case of front validation.
$(document).ready(function() {
$('form[debounce]').submit(function(e) {
const submiting = !!$(this).data('submiting');
if(!submiting) {
$(this).data('submiting', true);
setTimeout(() => {
$(this).data('submiting', false);
}, 2000);
return true;
}
e.preventDefault();
return false;
});
})
the best way to prevent multiple from submission is this
just pass the button id in the method.
function DisableButton() {
document.getElementById("btnPostJob").disabled = true;
}
window.onbeforeunload = DisableButton;
To do this using javascript is bit easy. Following is the code which will give desired functionality :
$('#disable').on('click', function(){
$('#disable').attr("disabled", true);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="disable">Disable Me!</button>
Most simple solutions is that disable the button on click, enable it after the operation completes. To check similar solution on jsfiddle :
[click here][1]
And you can find some other solution on this answer.
This works very fine for me. It submit the farm and make button disable and after 2 sec active the button.
<button id="submit" type="submit" onclick="submitLimit()">Yes</button>
function submitLimit() {
var btn = document.getElementById('submit')
setTimeout(function() {
btn.setAttribute('disabled', 'disabled');
}, 1);
setTimeout(function() {
btn.removeAttribute('disabled');
}, 2000);}
In ECMA6 Syntex
function submitLimit() {
submitBtn = document.getElementById('submit');
setTimeout(() => { submitBtn.setAttribute('disabled', 'disabled') }, 1);
setTimeout(() => { submitBtn.removeAttribute('disabled') }, 4000);}
Just to add to the possible answers without bypassing browser input validation
$( document ).ready(function() {
$('.btn-submit').on('click', function() {
if(this.form.checkValidity()) {
$(this).attr("disabled", "disabled");
$(this).val("Submitting...");
this.form.submit();
}
});
});
An alternative to what was proposed before is:
jQuery('form').submit(function(){
$(this).find(':submit').attr( 'disabled','disabled' );
//the rest of your code
});
<h3>Form</h3>
<form action='' id='theform' >
<div class='row'>
<div class="form-group col-md-4">
<label for="name">Name:</label>
<input type='text' name='name' class='form-control'/>
</div>
</div>
<div class='row'>
<div class="form-group col-md-4">
<label for="email">Email:</label>
<input type='text' name='email' class='form-control'/>
</div>
</div>
<div class='row'>
<div class="form-group col-md-4">
<input class='btn btn-primary pull-right' type="button" value="Submit" id='btnsubmit' />
</div>
</div>
</form>
<script>
$(function()
{
$('#btnsubmit').on('click',function()
{
$(this).val('Please wait ...')
.attr('disabled','disabled');
$('#theform').submit();
});
});
</script>
This is a clean Javascript code that prevents multiple valid submissions:
<script>
var form = document.querySelector('form');
form.onsubmit = function(e){
if(form.reportValidity())
// if form is valid, prevent future submissions by returning false.
form.onsubmit = (e)=> false;
return true;
}
</script>
Is there a php way to validate a form that goes submitted to another page before submitting and stay on same page if fields are not valid or if everything valid send post data to another page?
Example would be:
I am on page somesite.com/orderitems and there would be form like
<form method="post" id="orderform" action="somesite.com/shoppingcart">
<input type="number" name="numitems" id="numitems" value="1">
<input type="date" name="date" id="date">
</form>
So google chrome for example already knows to validate if you put in input field required value and to validate date and number fields. I have also a jquery datepicker so user can select date easily, and also jquery validator to validate fields before submit, but all this can be overridden and/or fail at some point.
So end point would be validation in php when form is submitted.
But what i am stumbled upon is that i can't use GET request in getting data on somesite.com/shoppingcart so i must send POST to that page, but if some of the field fail to validate, like wrong date or wrong date format, than i shouldn't even go (redirect or post) to somesite.com/shoppingcart, instead i should stay on the page somesite.com/orderitems and display the errors.
So is there a solution to something like this, what suggestions would you recommend. Can i post form to the same page and validate fields if, all is good than redirect to another page and pass POST data, or stay on same page and display error?
I will show you how this can be done via JavaScript/Ajax and PHP. I think it won't be difficult to learn doing it from this tutorial, but if some questions arise I am ready to help you.
JavaScript/Ajax request
First of all, we need to add "Submit" button to form and set "sendData()" function as its "onclick" listener. Which means each time you click on "Submit" button, "sendData()" function will execute. Also, we need to add 'class' attribute to 'number' and 'date' input elements, to get their values in more cleaner way.
<form method="post" id="orderform" action="somesite.com/shoppingcart">
<input type="number" class='myForm' name="numitems" id="numitems" value="1">
<input type="date" class='myForm' name="date" id="date">
<input type="Submit" value="Send" onclick = sendData(); return false;"/>
</form>
<script type="text/javascript">
function sendData()
{
var formElements = document.querySelectorAll(".myForm"); // We use 'class' attribute to get form elements (number and date).
var formData = new FormData(); // we create FormData object with which we can send data to "PHP" script (server side).
for(var i = 0; i < formElements.length; i++)
{
formData.append(formElements[i].name, formElements[i].value);
}
//AJAX Starts Here
var xmlHttp = new XMLHttpRequest(); // Create "ajax" object
xmlHttp.onreadystatechange = function() //This is to wait for response from your PHP script
{
if(xmlHttp.readyState === 4 && xmlHttp.status === 200) //And when status is OK use result
{
var responseText = xmlHttp.responseText; //here you save your response from server side.
if(responseText["Status"] === "OK") //if you send from server side that "Status" is OK, then you can go to that page
{
window.location.href = "somesite.com/shoppingcart";
}
else //otherwise you refresh page
{
window.location.reload();
}
}
}
xmlHttp.open("POST", "somesite.com/shoppingcart"); //set page value, where you want to send form values
xmlHttp.send(formData); //send actual data
}
</script>
PHP validation (to avoid manipulation/override on client-side)
When you validate values in server-side, set $_SESSION["Status"] = "OK".
After that if someone tries to "hack" your page and "change" your JavaScript functions to navigate to somesite.com/shoppingcart page, you will check:
somesite.com/shoppingcart
<?php
if($_SESSION["Status"] === "OK"])
{
//give permission
}
else
{
return false;
}
?>
i am also facing this problem. and i solve it by doing this
UPDATE
$(document).ready(function () {
$('#orderform').validate({
rules: {
numitems: {
required: true,
number: true
},
date: {
required: true,
date: true
}
}
});
$('#orderform input').on('keyup blur', function () {
if ($('#orderform').valid()) {
$("#button1").removeClass("submit");
//TRIGGER FORM
//$('#orderform').submit();
}
});
});
.submit{
user-select: none;
color:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jquery-validation#1.17.0/dist/jquery.validate.js"></script>
<form method="post" id="orderform" action="somesite.com/shoppingcart">
<input type="number" name="numitems" id="numitems"><br/>
<input type="date" name="date" id="date"><br/>
<span class="submit" id="button1">SUBMIT</span>
</form>
i Hope it helps.!
I have tried following code for make the required field to notify the required field but its not working in safari browser.
Code:
<form action="" method="POST">
<input required />Your name:
<br />
<input type="submit" />
</form>
Above the code work in firefox. http://jsfiddle.net/X8UXQ/179/
Can you let me know the javascript code or any workarround? am new in javascript
Thanks
Safari, up to version 10.1 from Mar 26, 2017, doesn't support this attribute, you need to use JavaScript.
This page contains a hacky solution, that should add the desired functionality: http://www.html5rocks.com/en/tutorials/forms/constraintvalidation/#toc-safari
HTML:
<form action="" method="post" id="formID">
<label>Your name: <input required></label><br>
<label>Your age: <input required></label><br>
<input type="submit">
</form>
JavaScript:
var form = document.getElementById('formID'); // form has to have ID: <form id="formID">
form.noValidate = true;
form.addEventListener('submit', function(event) { // listen for form submitting
if (!event.target.checkValidity()) {
event.preventDefault(); // dismiss the default functionality
alert('Please, fill the form'); // error message
}
}, false);
You can replace the alert with some kind of less ugly warning, like show a DIV with error message:
document.getElementById('errorMessageDiv').classList.remove("hidden");
and in CSS:
.hidden {
display: none;
}
and in HTML:
<div id="errorMessageDiv" class="hidden">Please, fill the form.</div>
The only drawback to this approach is it doesn't handle the exact input that needs to be filled. It would require a loop accross all inputs in the form and checking the value (and better, check for "required" attribute presence).
The loop may look like this:
var elems = form.querySelectorAll("input,textarea,select");
for (var i = 0; i < elems.length; i++) {
if (elems[i].required && elems[i].value.length === 0) {
alert('Please, fill the form'); // error message
break; // show error message only once
}
}
If you go with jQuery then below code is much better. Just put this code bottom of the jquery.min.js file and it works for each and every form.
Just put this code on your common .js file and embed after this file jquery.js or jquery.min.js
$("form").submit(function(e) {
var ref = $(this).find("[required]");
$(ref).each(function(){
if ( $(this).val() == '' )
{
alert("Required field should not be blank.");
$(this).focus();
e.preventDefault();
return false;
}
}); return true;
});
This code work with those browser which does not support required (html5) attribute
Have a nice coding day friends.
I had the same problem with Safari and I can only beg you all to take a look at Webshim!
I found the solutions for this question and for this one very very useful, but if you want to "simulate" the native HTML5 input validation for Safari, Webshim saves you a lot of time.
Webshim delivers some "upgrades" for Safari and helps it to handle things like the HMTL5 datepicker or the form validation. It's not just easy to implement but also looks good enough to just use it right away.
Also useful answer on SO for initial set up for webshim here! Copy of the linked post:
At this time, Safari doesn't support the "required" input attribute. http://caniuse.com/#search=required
To use the 'required' attribute on Safari, You can use 'webshim'
1 - Download webshim
2 - Put this code :
<head>
<script src="js/jquery.js"></script>
<script src="js-webshim/minified/polyfiller.js"></script>
<script>
webshim.activeLang('en');
webshims.polyfill('forms');
webshims.cfg.no$Switch = true;
</script>
</head>
I have built a solution on top of #Roni 's one.
It seems Webshim is deprecating as it won't be compatible with jquery 3.0.
It is important to understand that Safari does validate the required attribute. The difference is what it does with it. Instead of blocking the submission and show up an error message tooltip next to the input, it simply let the form flow continues.
That being said, the checkValidity() is implemented in Safari and does returns us false if a required filed is not fulfilled.
So, in order to "fix it" and also show an error message with minimal intervention (no extra Div's for holding error messages) and no extra library (except jQuery, but I am sure it can be done in plain javascript)., I got this little hack using the placeholder to show standard error messages.
$("form").submit(function(e) {
if (!e.target.checkValidity()) {
console.log("I am Safari"); // Safari continues with form regardless of checkValidity being false
e.preventDefault(); // dismiss the default functionality
$('#yourFormId :input:visible[required="required"]').each(function () {
if (!this.validity.valid) {
$(this).focus();
$(this).attr("placeholder", this.validationMessage).addClass('placeholderError');
$(this).val(''); // clear value so it shows error message on Placeholder.
return false;
}
});
return; // its invalid, don't continue with submission
}
e.preventDefault(); // have to add it again as Chrome, Firefox will never see above
}
I found a great blog entry with a solution to this problem. It solves it in a way that I am more comfortable with and gives a better user experience than the other suggestions here. It will change the background color of the fields to denote if the input is valid or not.
CSS:
/* .invalid class prevents CSS from automatically applying */
.invalid input:required:invalid {
background: #BE4C54;
}
.invalid textarea:required:invalid {
background: #BE4C54;
}
.invalid select:required:invalid {
background: #BE4C54;
}
/* Mark valid inputs during .invalid state */
.invalid input:required:valid {
background: #17D654 ;
}
.invalid textarea:required:valid {
background: #17D654 ;
}
.invalid select:required:valid {
background: #17D654 ;
}
JS:
$(function () {
if (hasHtml5Validation()) {
$('.validate-form').submit(function (e) {
if (!this.checkValidity()) {
// Prevent default stops form from firing
e.preventDefault();
$(this).addClass('invalid');
$('#status').html('invalid');
}
else {
$(this).removeClass('invalid');
$('#status').html('submitted');
}
});
}
});
function hasHtml5Validation () {
return typeof document.createElement('input').checkValidity === 'function';
}
Credit: http://blueashes.com/2013/web-development/html5-form-validation-fallback/
(Note: I did extend the CSS from the post to cover textarea and select fields)
I use this solution and works fine
$('#idForm').click(function(e) {
e.preventDefault();
var sendModalForm = true;
$('[required]').each(function() {
if ($(this).val() == '') {
sendModalForm = false;
alert("Required field should not be blank."); // or $('.error-message').show();
}
});
if (sendModalForm) {
$('#idForm').submit();
}
});
The new Safari 10.1 released Mar 26, 2017, now supports the "required" attribute.
http://caniuse.com/#search=required
You can add this event handler to your form:
// Chrome and Firefox will not submit invalid forms
// so this code is for other browsers only (e.g. Safari).
form.addEventListener('submit', function(event) {
if (!event.target.checkValidity()) {
event.preventDefault();
var inputFields = form.querySelectorAll('input');
for (i=0; i < inputFields.length; i++) {
if (!inputFields[i].validity.valid) {
inputFields[i].focus(); // set cursor to first invalid input field
return false;
}
}
}
}, false);
Within each() function I found all DOM element of text input in the old version of PC Safari, I think this code useful for newer versions on MAC using inputobj['prpertyname'] object to get all properties and values:
$('form').find("[required]").each(function(index, inputobj) {
if (inputobj['required'] == true) { // check all required fields within the form
currentValue = $(this).val();
if (currentValue.length == 0) {
// $.each((inputobj), function(input, obj) { alert(input + ' - ' + obj); }); // uncomment this row to alert names and values of DOM object
var currentName = inputobj['placeholder']; // use for alerts
return false // here is an empty input
}
}
});
function customValidate(){
var flag=true;
var fields = $('#frm-add').find('[required]'); //get required field by form_ID
for (var i=0; i< fields.length;i++){
debugger
if ($(fields[i]).val()==''){
flag = false;
$(fields[i]).focus();
}
}
return flag;
}
if (customValidate()){
// do yor work
}
I'm using Ajax to test if the Username on a Register form is too short.
Right now it just does this:
if (str.length<6)
{
document.getElementById("txtHint").innerHTML="Too short";
return;
}
How do I add an action above that doesn't let the user submit?
<form action="/insert/insert-user.php" method="post">
<input type="text" name="user" onkeyup="showHint(this.value)"/>
In the CheckUserName function, add your ajax code and return true or false. If It's false, it won't submit.
<form action="/insert/insert-user.php" onsubmit="CheckUserName()" method="post">
You may try adding a form name and onsubmit event to your form.
<form name="formName"action="/insert/insert-user.php" method="post" onsubmit="validate()">
function validate() {
if (document.formName.user.value.length < 7) {
// Display your message in your division
return false;
}
}
You must also repeat the check in php since the user may have Javascript disabled and for security measure:
if ($_POST['your_submit_button']) {
if (strlen($_POST['user']) < 7) {
$submit = false;
die ("<div style='color: red;'>Too short</div>");
}
}
Give your error div a class lets say 'error' and on submitting the form call another function in which you check the if error class have text by JQuery. If the class have the text just return false and your form will not be submitted