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.
Related
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.
I need to validate a form using JavaScript. The form keep changes since I am using data from a field name table to print each field (like name, address, phone no.). I'm using a loop to print the label for field and corresponding text input tag. (eg. name : textbox to enter name, phone no : textbox to enter phone no.) And at last getting these values in an array when submitting the form and entering into details table.
Following is the code for printing each field and text box:
while ($row=mysql_fetch_array($result)){
echo'<labelfor='.$row['field_name'].'name=field_id>'.$row['field_name'].':</label>';
echo'<inputtype="text" name=field_name[]id="'.$row['field_id'].'":value="'.$row['field_value'].'" size="20" class = "inpBox" >';
}
Now I need to check whether these fields are empty using JavaScript and then change the style of that particular text box. Any help will be greatly appreciated.
You'll want to hook on the submit event for your form. You could then do something like:
This is for jQuery:
$("form").submit(function{
$('input[type="text"]',"form").each(function(){
var $me = $(this);
var status = true;
if($me.val() == ""){
$me.addClass("input-validation-error");
status = false;
}
//Return status. True=Form is valid, False=Form is NOT valid
return status;
});
});
You can read more here: http://api.jquery.com/submit/
To get the values for javascript, you could do something like:
var inputs = document.getElementsByTagName("input");
for (var i = 0; i < inputs.length; i++) {
var me = inputs[i];
if(me.value == "") {
me.className = "input-validation-error";
}
}
Generally Google "dynamic form validation"
For your particular case you will be interested in
See https://developer.mozilla.org/en/DOM/document.getElementsByClassName
and loop over all elements. You may want to add extra properties to your entry fields to define if it needs validation and the type of validation needed.
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"
});
I have the following code to check for form data and I can't figure out why its not working.
<script type="text/javascript">
function checkStuff() {
// By default, we plan to submit the form.
var formOkay = 1;
// Check to see if field_1 has a value. If not, we note that by changing our variable.
if(document.getElementById('requestorfirstname').value == '')
formOkay = 0;
// Let the user know something is wrong somehow. An alert is easiest.
alert('Requestor Name Required!');
// If you return true the form will submit. If you return false it will not.
if(formOkay == 1) {
return true;
} else {
return false;
}
}
</script>
Now here is the html form piece its checking onsubmit.
<input type="text" name="requestorfirstname" />
Thanks for the help!
document.getElementById looks for elements by ID. Your field doesn't have an ID, it has a NAME.
document.getElementById selects an element by id, not by name.
Some ways to solve the problem:
Add id="requestorfirstname" to the input element.
Use document.getElementsByName('requestorfirstname')[0]. getElementsByName returns a list, hence [0].
Use the document.querySelector('[name="requestorfirstname"]') method.
Get a reference to the form, and access the element using the .elements collection.For example, if your page has only one form:
document.forms[0].elements['requestorfirstname']
A name attribute on an HTML element is NOT the same as an id. You have no id on your input field, so there's no way for getElementById to find it. Change the element to:
<input type="text" name="requestorfirstname" id="requestorfirstname" />
^^^^^^^^^^^^^^^^^^^^^^^^ - add this
ajax is not yet sothin i master.
I have two forms field
code :
name :
and the submit button like :
<form><input type=text name=code><input type =text name=name/></form>
I would like in php/jquery to check if the code the user fill exist in a table of my db.
If it does not exits, when the user leave the textfield to fill the next one, i would like to print a message like: this code is not in the db and then clean the fied. Until the user provide a valide code.
If your php service returns true or false for validation.
and the placeholder for the error is a label called
then an example (in jQuery) would be
$(document).ready(function() {
$("form").submit(function(e) {
var code = $("input[name='code']");
var error = $("#error");
e.preventDefault();
var form = this;
$.getJSON('urlToPhp',
{ code: code.val() },
function(valid) {
if (!valid) {
error.text(code.val() + ' is not found try another code...');
code.val('');
} else {
form.submit();
}
}
);
});
});
I've created a simple example at http://jsfiddle.net/nickywaites/e4rhf/ that will show you have to create a jQuery ajax post request.
I'm not too familiar with php so that part of it I'll have to leave aside although you can use something along the lines of $_POST["Name"].
Here is php example that I googled http://php4every1.com/tutorials/jquery-ajax-tutorial/ that might be better for you.