Limiting range of input field - php

Though it is a very common question. I have one input field in which the data entered must be between 1 and 150.
Problem is I am already using some validations on that. That validation is being used by many other input fields. So I cannot change that. It is the num() function.
On one field mesure I want to add extra functionality. I tried it with validate.
I don't know how to merge these two validations for only one input field using both function in document.ready.
I can do it in either jQuery or PHP.
<input type="text" name='mesure' class="numbersonly" maxlength="3" onblur =" validate()"/>
function num() {
$(".numbersonly").bind('keypress', function(e) {
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
$("#errmsg").html("numbers please");
return false;
}
});
}
function validate()
{
if( document.form.mesure.value >150 )
{
alert( "out of range!" );
document.form.mesure.focus() ;
return false;
}
}

Why not using onkeypress/onkeyup, check it using the validate function.
But remember that javascript is not the real solution for limitation - People can turn of or change the javascript. Also use php for checking the value.

For example, if your input field that you want to limit has the id #text, you can use
if($('#text').val().length>150){
//do stuff here
}
As you will probably post the entered value to some place in the backend, the real validation must happen in php. There, you can do something like
<?php
if(strlen($_POST['text'])>150){
echo "too long";
exit;
}
//do other backend stuff here
?>
Using javascript for validation is only good in so far as it gives the user immediate feedback whether he did something wrong. However, a client can always see client side code like jQuery/Javascript, so for ultimate validation use php.

Related

prevent characters in text box in php using jquery

I want to prevent user to input few characters like ; and \ and /. I now it need jquery to do, but i cant find one
The jquery will used in name. zip code input to prevent such characters etc.
please show me an example as i new to jquery and php
You can use event.which to getting code of pressed key and use return false to preventing enter of character.
$("input").keydown(function(e) {
if (e.which === 186 || e.which === 191 || e.which === 220){
console.log("This character can't entered");
return false;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input />
This should do the job. I hope you can read this simple code:
// select css classes 'input' and assign onKeyDown event to them
$(".input").keydown(function(event) {
// check what key is pressed. dot is not allowed in this case
if ( event.keyCode === 190) {
// prevent event to happen
event.preventDefault();
}
});
On the bottom of this page there is a small table for some codes and also an input field which shows you key code for particular key. Just as a helper, to let you find codes for wished key faster.

PHP JQuery and Jeditable

Just a quick question regarding this issue i am having. I am using jeditable to edit in place some fields on a page. This is working perfectly. Now I wish to implement some data checking. I have my php code to check the data entered and if its correct, it updates that database, and if it isn't it will return the error. The issue I am having is I want it to spit out the error to tell them but when they click the field again to edit it, it shows the error in the field until a page refresh. What i want it to do is have the same data in the field when they click on it after the error occurs instead of having to refresh the page then click the field again to edit it. Perhaps there is a way to return back the error and pass that into a tooltip of some sort above the field? Of course the way jeditable works is the div is surrounding the field then i have some js calling on my update.php file, this parses what jeditable passes to it and returns a $value to be error checked and by default if it is fine it simply at the bottom of the php "return $value;" to be put back int he field after its been saved in the DB.
Hopefully someone can understand what I am asking here and any assistance would be appreciated.
Easiest way is probably to do some client side validation. Right now you are doing server side validation by checking in PHP when the form is submitted. What are you checking for?Without code it is hard to give you a good example of client side validation.
Basic field checking:
var check_field = $("#field").val();
if (!check_field) { alert("Error message"); } else
{
// submit POST or whatever
}
Edit
Since the MAC address validation algorithm is already written server side, I recommend a separate ajax POST request that calls the checker function. Take the result of that request (true, false) and check it client side. If true, proceed with the update call.
Example:
$("#form").submit(function() {
var mac = $("#macfield").val();
if (!mac) { alert("MAC address can't be empty!"); } else
{
$.POST("checkmacaddress.php", {macval: mac}).success(function(a){
//assuming a comes back as a bool
if (!a) { alert("Invalid MAC!"); } else
{
// if the checker returned true, update the record
$.POST("update.php" ...);
}
});
} });
This doesn't include the checkmacaddress.php but you should be able to handle that if you already have the function on hand.
Hate when I do this, post here then figure out the answer myself...but at least if someone has the same issue they will see it. I found out about the jeditable onsubmit functions...i am using a tooltip to show on hover when editing the field so this will set the tooltip to the error and not submit the data unless its a valid mac.
function isMAC(value) {
teststr = value;
regex=/^([0-9a-f]{2}([:-]|$)){6}$|([0-9a-f]{4}([.]|$)){3}$/i;
if (regex.test(teststr)){
return true;
}
else {
return false;
}
}
$(".edit_mac").editable("edit_mac.php", {
onsubmit: function(settings, data) {
var input = $(data).find('input');
var value = input.val();
if (isMAC(value)) {
return true;
} else {
//display your message
$("#tooltip").html("Bad MAC Address...");
return false;
}
},
indicator : "Saving...",
submitdata: { _method: "put" },
submit : 'Save',
cssclass : "editable",
type : "text"
});

Keyup if statement for indexOf string acting odd?

I've got a small problem with the following code:
$('#body').keyup(function(){
var i = $('#body').val();
if(i.toLowerCase().indexOf("contact") >= 0){
$('#tosviolation').fadeIn('fast');
$('#sendForm').attr('action','send.php?f=1');
$('.toscontent').html("TOS Breach!");
} else {
$('#tosviolation').fadeOut('fast');
$('#sendForm').attr('action','send.php?f=0');
}
if(i.toLowerCase().indexOf("#") >= 0){
$('#tosviolation').fadeIn('fast');
$('#sendForm').attr('action','send.php?f=1');
} else {
$('#tosviolation').fadeOut('fast');
$('#sendForm').attr('action','send.php?f=0');
}
});
It checks whether #body (textarea) contains the values "contact" or/and "#", and if this textarea does contain said values, it pops up / flashes a div telling the user that they're violating the TOS. With the "#", the box stays there when the user types it, yet when the user types "contact", the box just flashes a few times and goes away, I'm guessing since "#" is 1 char long, and "contact" is 7 chars long, it's something to do with that.
Then again, this is quite strange? I was intending it to just fadeIn() and stay faded in. I didn't mind the flash, because of course, on keyup it'll have to run the function every time the user taps a key, so that's fine, but I can't figure out how to keep it there when the user types "contact" somewhere in the textarea. Also, the other part where the it's using the .attr() is directing the user to send.php, if it does contain "contact","#" -- Then it pushes them to send.php?f=1, and if not, then send.php?f=0 -- #sendForm is the ID of a form tag I have earlier, I assume this already works fine.
Does anyone know how to get the box to stay there once it's pulled up with the data "contact" ?
Try this. Remember, setting the attribute of a form and relying on it for server-side processing is dangerous - the end user can easily fiddle with this before posting. You should validate again with the server and not use any GET variables sent with the form.
$('#body').keyup(function () {
var i = $('#body').val();
if (i.toLowerCase().indexOf("contact") >= 0 || i.toLowerCase().indexOf("#") >= 0) {
$('#tosviolation').fadeIn('fast');
$('#sendForm').attr('action', 'send.php?f=1');
$('.toscontent').html("TOS Breach!");
} else {
$('#tosviolation').fadeOut('fast');
$('#sendForm').attr('action', 'send.php?f=0');
}
});
The problem is that when you're typing "contact", you don't have the "#" symbol. So your first if statement for contact evaluates to true, and fades in #tosviolation. However, the next if statement evaluates to false, so it fades it back out straight away. You'll need to restructure your if statements (likely using an OR condition, rather than two separate if statements) to avoid this.
Something like this should work:
$('#body').keyup(function() {
var i = $('#body').val();
var contact = i.toLowerCase().indexOf("contact");
var atsymbol = i.toLowerCase().indexOf("#");
if (contact >= 0 || atsymbol >= 0) {
$('#tosviolation').fadeIn('fast');
$('#sendForm').attr('action', 'send.php?f=1');
if(contact >= 0) {
$('.toscontent').html("TOS Breach!");
}
} else {
$('#tosviolation').fadeOut('fast');
$('#sendForm').attr('action', 'send.php?f=0');
}
});
Why don't you just check this once, when the field loses focus or before formsubmit? This is easier and cleaner then checking on every keyup event.
I strongly recommend to check the Input on serverside again. simply adding f=1 or f=0 can be manipulated easily. Also think about what happened if the user disabled js.

How to prevent a "space" from searching MySQL database?

Currently, when someone just hits the space key and hits enter it will go to the next page but not search anything - I want to prevent the search altogether. What is the best way to accomplish this? I don't want to prevent spaces from being used (ie: How do I fix this?) - I just dont want spaces themselves to allow a search.
Wrap your query variable in an empty condition:
if(!empty(trim($_POST['searchterm']))
{
// do search
}
Use JavaScript and trim leading spaces in the submit (onsubmit) event handler:
var searchField = document.getElementById('search'); // or whatever the id of the field is
if(searchField.value.replace(/^\s+/, '').length === 0) {
return false; // or evt.preventDefault().
}
It should be okay to rely on client-side validation here because if the user wants to fool the search engine then they won't mind being brought to a blank page. If there's an actual server-side problem in allowing this, then perform the same check server-side:
if(!isset($_REQUEST['search']) || !trim($_REQUEST['search'])) {
// Don't perform the search
}
In addition to #AlienWebguy answer you can use JavaScript to do client side validation in order to stop the page from even getting to the back end. Its definitely a good practice to do the validation on the client side AND server side.
Live Demo
form.onsubmit = function(){
if(input.value.replace(/^\s/,"").length === 0){
return false;
}
}
Just take the string, trim the initial and final spaces and check the length; if length is 0, don't submit the form.
If you are procecssing it with php on the backend you can just use trim($input), but for a better user experince use javascript. Set a form validator so it won't submit unless there is something other than whitespace.
<form onsubmit="return verify()">
<input id="foo" name="foo" />
<input type="submit" />c
</form>
<script type="text/javascript">
function verify() {
if (document.getElementById("foo").value.match(/[^\s]/) == null) {
alert('only whitespace');
return false;
} else {
alert('found substance');
return true;
}
}
</script>

Form validation

I want to validate my registration form but i have default values for every text input. Tried all possible ways with jquery validate plugin. It's hard to understand how to use it (I'm newbie to js) What i want to do, is ignore the default values and validate form. My form looks like that
<from id="reg">
<input class="part1 default" type="text" name="fname" id="fname" value="Adınız (First Name)"/>
<input class="part1 default" type="text" name="mname" value="Atanızın adı (Middle name)"/>
</form>
I'm using this piece of code for this form
var defaultValues = {
'fname': 'Adınız',
'mname': 'Atanızın adı',
'lname': 'Soyadınız',
'phone': 'Telefon',
'email': 'Email',
'pwd':'Şifrə',
'region':'Rayon',
'school':'Məktəb',
'login':'Istifadəçi adı',
'class':'Sinif',
'subject':'Fənnin adını daxil edin',
'dob': 'Date of Birth'
};
$('input').live('focus', function() {
var el = $(this);
if (el.hasClass('default')) {
el.removeClass('default').val('');
}
if (el.attr('id') === 'dob') {
$(this).mask('99.99.9999', {placeholder:' '});
}
});
$('input').live('blur', function() {
var el = $(this);
var name = el.attr('name');
// Really we only want to do anything if the field is *empty*
if (el.val().match(/^[\s\.]*$/)) {
// To get our default style back, we'll re-add the classname
el.addClass('default');
// Unmask the 'dob' field
if (name == 'dob') {
el.unmask();
}
// And finally repopulate the field with its default value
el.val(defaultValues[name]);
}
});
/*validation*/
$('#reg').submit(function (event)
{
if ($('#fname').val() == defaultValues['Adınız'] || $.trim($('#pwd').val()) == '')
{
alert('Please enter the name!');
return false;
}
else
{
if ($('#fname').val().length < 2)
{
alert('The name must be >2 letters!');
return false;
}
}
});
The last part as you see is the validation. I have a feq questions about it
Lets say we wrote if's for all possible cases. What if allright and
we want to continue submitting process? Do i need to write new if
for it and end this if with "return true?"
I used this piece of code but it always gives me the same error
message "Please enter a password!" even if all input fields are
filled. How can we modify this code to alert the array of errors?
for example if my pass is wrong type and name field unfilled the script will
show 2 errors at once. I thought about logic too: For example every
time when some case is true then it pushes to array the error
message and when it finishes checking all cases, shows the error
array. But can't realise it.
How to validate email field, and date of birth field (looks like "19.16.2010")?
Instead of placing the default value in a "value" attribute, why not set it as the "placeholder".
<input type="text" name="fname" id="fname" placeholder="Adınız (First Name)"/>
Then you can just do regular validation...
What if allright and we want to continue submitting process? Do i need to write new if for it and end this if with "return true?"
Yes. return true;
I used this piece of code but it always gives me the same error message "Please enter a password!" even if all input fields are filled. How can we modify this code to alert the array of errors? for example if my pass is wrong type and name field unfilled the script will show 2 errors at once.
You need to collect all errors first and then display a message with all errors, e.g. with a composite data strucuture like an array.
I thought about logic too: For example every time when some case is true then it pushes to array the error message and when it finishes checking all cases, shows the error array. But can't realise it. How to validate email field, and date of birth field (looks like "19.16.2010")?
You need to provide a validation routine for each type of data. You can then call the according function per each field that contains that data type:
form element -> data-type -> validation function
Maybe you should just use the jquery validation plugin to spare the hassles? I think you're not the first one with this problem, so it's probably worth to dig in.

Categories