I have a simple php and jquery contact form (3 fields: name - email - message), whose input field are coded like this:
<input type="text" name="contactName" id="contactName" value="<?php if(isset($_POST['contactName'])) echo $_POST['contactName'];?>" class="requiredField"/>
I'd like those field to have a default value, rather than being empty. At the same time i wouldn't trust using the placeholder attribute, since it is not universally supported.
I found this jquery script that does the job in an excellent way:
<script>
$(function() {
$( ".contact_form_field" )
.focus(function() {
var $this = $(this);
if (!$this.data('default')) {
$this.data('default', $this.val());
}
if ($this.val() == $this.data('default')) {
$this.val('')
.css('color', '#000');
}
})
.blur(function() {
var $this = $(this);
if ($this.val() == '') {
$(this).val($this.data('default'))
.css('color', '#666');
}
})
.css('color', '#666')
});
</script>
However, to make it work i had to change the value attributes of the field to the desidered placeholder text:
<input type="text" name="contactName" id="contactName" value="Name" class="requiredField"/>
This, predictably, seems to interfere with the form action that should prevent the mail being sent if there are empty fields:
if(trim($_POST['contactName']) === '') {
$hasError = true;
} else {
$name = trim($_POST['contactName']);
}
I thought i just had to change the string to
if(trim($_POST['contactName']) === 'Name') { or
if(trim($_POST['contactName']) == 'Name') { or
but it doesn't seem to work. The mail gets sent even if the field is left untouched (not empty, since the "Name" text is displayed).
I am at a loss to understand what i'm doing wrong, any input (sorry for the pun x_x) would be greatly appreciated.
Placeholders are quite ready to use today. But if you still don't trust it you can use old solution based on onfocus and onblur attributes. Here's an example:
<input onfocus="if(this.value==='default value') this.value=''" onblur="if(this.value==='') this.value='default value'">
create an array with all the default values and test to see if the submitted value is part of the default value
$defaultValue = array('', 'Name');
if(in_array(trim($_POST['contactName']), $defaultValue) {
$hasError = true;
} else {
$name = trim($_POST['contactName']);
}
Related
Here is my input field disabled code
<input type="text" class="empl_date form-control" id="staffid" name="staffid" value="<?php echo $employeeworks[0]['employeeCode'];?>" arsley-maxlength="6" placeholder=" Schedule Date" disabled />
How can i prevent inspect element option in this field?
No it's not possible.
Code inspectors are designed for debugging HTML and Javascript. They will always do show the live DOM object of web page. It means that it reveals the HTML code of everything you see on the page, even if they're generated by Javascript.
As mentioned in other answers, it can't be prevented fully, once it is in the browser, user can manipulate it.
Rather than thinking how to prevent the inspect element or dev tools being used on your input, you should think about your goal, what do you want to achieve with this?
If you want to prevent from input value being changed, use some hash generated on server side, that includes value from your staffid field and store it in hidden input.
When user submits the form, just regenerate hash using staffid value and hash value from input. If they don't match, user has manipulated the staffid input manually.
Example:
<input type="text" class="empl_date form-control" id="staffid" name="staffid" value="<?php echo $employeeworks[0]['employeeCode'];?>" arsley-maxlength="6" placeholder=" Schedule Date" disabled />
<input type="hidden" name="hash" value="<?php echo md5($employeeworks[0]['employeeCode'] . 'some salt to avoid user just generating hash with md5 using value only'); ?> />
and then on submission:
$staffid = filter_input(INPUT_POST, 'staffid');
$hash_input = filter_input(INPUT_POST,'hash');
$hash_check = md5($staffid . 'some salt to avoid user just generating hash with md5 using value only');
if($hash_input !== $hash_check){
//looks like the user manipulated staffid value, throw a validation error
}
You can prevent inspect by right click.
This way to prevent right click
document.addEventListener('contextmenu', function(e) {
e.preventDefault();
});
If user press F12 and click arrow button and inspect, it still ok.
You also can prevent F12 by this code
document.onkeydown = function(e) {
if(event.keyCode == 123) { //F12 keycode is 123
return false;
}
}
Actually, you can not restrict user to check inspect element of any specific element but you can disable completely. Check below code which will not allow user to open debugger and not even page source.
document.onkeydown = function(e) {
if(e.keyCode == 123) {
e.preventDefault();
return false;
}
if(e.ctrlKey && e.shiftKey && e.keyCode == 'I'.charCodeAt(0)) {
e.preventDefault();
return false;
}
if(e.ctrlKey && e.shiftKey && e.keyCode == 'C'.charCodeAt(0)) {
e.preventDefault();
return false;
}
if(e.ctrlKey && e.shiftKey && e.keyCode == 'J'.charCodeAt(0)) {
e.preventDefault();
return false;
}
if(e.ctrlKey && e.keyCode == 'U'.charCodeAt(0)) {
e.preventDefault();
return false;
}
}
But this code also has some missings as well. Hope it helps you.
Try This,
<input type="text" oncontextmenu="return false;" class="empl_date form-control" id="staffid" name="staffid" value="<?php echo $employeeworks[0]['employeeCode'];?>" arsley-maxlength="6" placeholder=" Schedule Date" disabled />
If I submit blank fields it still adds it into database. I made a loop to check if everything is on place but it keeps redirecting it to error page. I've been struggling with this almost 2 hours but cant find a solution.
Links are here since i can post more than 2 :
Try to set
Don't allow nulls
in the column property of table. It can be done during the table design or Edit table Design in the database.
Hope this helps.
You using empty(). http://us3.php.net/empty
This only returns false if NULL, FALSE, or not exists, NOT if empty string.
You should be doing this:
foreach($required as $post){
if ($_POST[$post] == "") {
die(header("refresh:0.5;url=error.php"));
}
}
However, I don't know why you don't just put this over the entire code block so it only gets executed on submit of the form. Then you don't have to keep rechecking it.
if (isset($_POST)) { //or a specific $_POST variable if multiple submit paths
//code here
}
Additionally, you should edit your question to include the relevant code in the question or in the future, searchers may discover that your pastebin link no longer works.
I think in any way you should make some client-side validation on empty field like jQuery functions :
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
$("form").submit(function(){
if($("#first_name").val() == ''){
alert("First name cann't be empty");
return false;
}else if($("#last_name").val() == ''){
alert("Last name cann't be empty");
return false;
}else if($("#email").val() == ''){
alert("Email cann't be empty");
return false;
}else if($("#password").val() == ''){
alert("Password name cann't be empty");
return false;
}
});
});
</script>
You're trying to get indexes on $_POST array that doesn't exist, so correct your $required array and put fields names not the variables names, just like this in process.php:
$required = array('first_name','last_name','password','email');
foreach($required as $post){
if($post = empty($_POST[$post]) || $_POST[$post] == ""){
die(header("refresh:0.5;url=error.php"));
} elseif($required != empty($_POST)) {
echo "";
}
}
I think yor a looking for something like,
if(isset($_POST['field1']) && !$_POST['field1'] =="")
{
//your codes goes here
}
Maybe You have done something like
<input type=text name=name1 value ="" />
If so, Please do it like,
<input type=text name=name1 />
This will not send name1 to your page;
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
I'm trying to validate a form using Ajax and onchange function. Basically I want automatic validation once the focus is gone from the input box. Then it will state an error if it's blank / invalid entry.
For some reason the validation works for invalid entries but won't work for empty inputs on first try (meaning if i refresh page and go to second field box by tab, there's no error). The funny thing is the empty error works fine after i erase an entry. I've tried using $var = "" or empty($var) but I still get the same results.
Here's the php part:
if(isset($_GET["isbn"]) )
{
$isbn = $_GET["isbn"];
$error="";
if(empty($isbn) || !preg_match("/^\d{12}$/", $isbn) )
{
$error .= "Please enter a valid ISBN";
echo $error;
}
else
echo $error;
}
Here's the rest:
<script type="text/javascript">
function validateIsbn(keyword)
{
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if(xhr.status == 200 && xhr.readyState == 4)
{
var res = xhr.responseText;
document.getElementById("err1").innerHTML = res;
}
}
xhr.open("get","validate_isbn.php?isbn=" + keyword,true);
xhr.send();
}
</script>
<form method="get" action="">
<label class="top-label">ISBN:</label>
<input name="isbn" id="isbn" type="text" onchange="validateIsbn(this.value)"/>
<div id="err1"> </div>
<p></p><p></p>
You say you want automatic validation once the focus is gone from the input box. The event triggered in that case is onblur, not onchange.
I have registration form on my website that, using jquery I append default values to, and onFocus/blur the default values hide and show accordingly.
My problem is that when the form is submitted and has kicked back errors using php validation, I am unable to show the posted values in the fields. The javascript seems to write over the posted data that is echoed using php in the input value.
When I look at the page source after posting my form I see that in the value of the input I do appear to have the posted value, the value that I want shown. Example:
<input type="text" name="first_name" value="Harry" />
PHP has done it's work in echoing the posted data into the value of my input. Then Javascript changes it so that instead of the user seeing their name (Harry in this example) they once again see the default jquery appended "First name".
This happens even though I have a value in the input.
How can I modify my Javascript to take note of the value of my input and not write over it?
This is the code so far:
$(document).ready(function() {
$('input[name=first_name]').val('First name');
$('input[name=last_name]').val('Last name');
$('input[name=email_address]').val('Email address');
// cache references to the input elements into variables
var passwordField = $('input[name=password]');
var emailField = $('input[name=email_address]');
var firstnameField = $('input[name=first_name]');
var lastnameField = $('input[name=last_name]');
// get the default value for the fields
var emailFieldDefault = emailField.val();
var firstnameFieldDefault = firstnameField.val();
var lastnameFieldDefault = lastnameField.val();
// add a password placeholder field to the html
passwordField.after('<input id="passwordPlaceholder" type="text" value="Password" autocomplete="off" />');
var passwordPlaceholder = $('#passwordPlaceholder');
// show the placeholder with the prompt text and hide the actual password field
passwordPlaceholder.show();
passwordField.hide();
// when focus is placed on the placeholder hide the placeholder and show the actual password field
passwordPlaceholder.focus(function() {
passwordPlaceholder.hide();
passwordField.show();
passwordField.focus();
});
// and vice versa: hide the actual password field if no password has yet been entered
passwordField.blur(function() {
if(passwordField.val() == '') {
passwordPlaceholder.show();
passwordField.hide();
}
});
// when focus goes to and moves away from the fields, reset it to blank or restore the default depending if a value is entered
emailField.focus(function() {
if(emailField.val() == emailFieldDefault) {
emailField.val('');
}
});
emailField.blur(function() {
if(emailField.val() == '') {
emailField.val(emailFieldDefault);
}
});
firstnameField.focus(function() {
if(firstnameField.val() == firstnameFieldDefault) {
firstnameField.val('');
}
});
firstnameField.blur(function() {
if(firstnameField.val() == '') {
firstnameField.val(firstnameFieldDefault);
}
});
lastnameField.focus(function() {
if(lastnameField.val() == lastnameFieldDefault) {
lastnameField.val('');
}
});
lastnameField.blur(function() {
if(lastnameField.val() == '') {
lastnameField.val(lastnameFieldDefault);
}
});
});
$('input[name=first_name]').val('First name');
This unconditionally sets the value of that element to First Name. It's not a "only set the value if it's empty", it's "set the value to First Name, regardless of what it's in there".
You'd need something like this to preserve what's in there:
if ($('input[name=first_name]').val() == '') {
$('input[name=first_name]').val('First name');
}
instead, which would only reset the field's value if it starts out empty.
Just get some placeholder plugin, your code repeat itself too much and still does not do what you need
This is just what you need:
http://plugins.jquery.com/project/input-placeholder
With it your code will look very clear and simple, like:
<input type="text" name="first_name" placeholder="First Name" />
<input type="text" name="last_name" placeholder="Last Name" />
<input type="text" name="email_address" placeholder="Email" />
<script>
$(function(){
$('input[placeholder]').placeholder();
})
</script>
Instead all of your javascript
on ready function your are setting some values before your default values
$('input[name=first_name]').val('First name');
$('input[name=last_name]').val('Last name');
$('input[name=email_address]').val('Email address');
so your defalut values cannot be empty
This is how i would do it so it would be more dynamic and less code.
<input type="text" name="first_name" rel="First Name" value="<?=$first_name?>" />
<input type="text" name="last_name" rel="Last Name" value="<?=$last_name?>" />
<input type="text" name="email" rel="Email" value="<?=$email?>" />
$(function(){
$('input').each(function(){
var val = $(this).val(),
rel = $(this).attr('rel');
$(this).focus(function(){
if(val === rel){
$(this).val('');
}
});
$(this).blur(function(){
if(val === ''){
$(this).val(rel);
}
});
if(val === ''){
$(this).val(rel);
}
});
});
With the minimum changes:
if($('input[name=first_name]').val()!='')
$('input[name=first_name]').val('First name');
if($('input[name=last_name]').val()!='')
$('input[name=last_name]').val('Last name');
if($('input[name=email_address]').val()!='')
$('input[name=email_address]').val('Email address');
Another cool way:
if($('input[name=first_name]').val()!='') {
$('input[name=first_name]').val('First name');
$('input[name=first_name]').class('init');
}
if($('input[name=last_name]').val()!='') {
$('input[name=last_name]').val('Last name');
$('input[name=last_name]').class('init');
}
if($('input[name=email_address]').val()!='') {
$('input[name=email_address]').val('Email address');
$('input[name=email_address]').class('init');
}
var initVals = new Array();
$("form input").each( function (i) { initVals[i] = this.value; } );
$("form input").focus( function () {
if ( $(this).hasClass("init") ){
$(this).removeClass("init");
$(this).val("");
}
} );
$("form input").blur( function (i) {
if ( $(this).val() == "" || $(this).val() == initVals[$("form input").index(this)] ){
$(this).addClass("init");
$(this).val( initVals[$("form input").index(this)] );
};
} );
Don't forget to use hasClass("init") or similar to avoid sending inputs with its default value.