Writing a summarized validation javascript code - php

I have an HTML page on the admin site for managing user on a HTML/Javascript/PHP system that runs on browsers. I have close to 20 inputboxes because on one page i have combined several forms of new_user, forgot_password, Change_password and Edit_user_details.
This code is what i used to check the username's empty field, this means i have to write 20 of this lines;
My concern is--> How do i write a short, summarized but effective javascript code to check on empty fields. (I will also need to validate fields like digits, numbers, length, emails etc)
function RequiredFields(){
var username=document.forms["login"]["username"].value;
if (username==""||username==null){
alert("empty username")
document.login.username.focus();
if(document.all||document.getElementById){
document.login.username.style.background="pink";
}
return false;
}
}

You can use jQuery to check for empty fields, have a look at this code:
function Validate() {
$('form input[type="text"]').each(function(){
if (this.value=="")
alert('Value Required');
});
}
To validate things like emails, numbers etc, you would need to write a separate function for those particular text boxes.

See here: http://jsfiddle.net/TgCbB/1/
HTML
<input type="text" id="username" class="required" data-default="User Name"/>
<input type="text" id="email" class="required email" data-default="Email"/>
<input type="text" id="digits" class="required digits" data-default="Integer"/>
The important thing to note here is the class attribute, which indicates how it should be validated. (You could do this with a data- attribute, which would be better, but I used class for backwards compatibility).
You can now, with plain javascript, validate like so:
function validate(e){
var invalid = [];
var required = document.getElementsByClassName("required");
for (var i = 0; i < required.length; i++){
var req = required[i];
var val = req.value || "";
var def = req.hasAttribute("data-default") ? req.getAttribute("data-default") : "";
if (val == "" || val == def)
invalid.push(req);
req.className = req.className.replace(" invalid","");
}
var digits = document.getElementsByClassName("digits");
for (var i = 0; i < digits.length; i++){
var dig = digits[i];
var val = Number(dig.value || "");
var rem = val - Math.floor(val);
if (rem != 0)
invalid.push(dig);
dig.className = dig.className.replace(" invalid","");
}
var emails = document.getElementsByClassName("email"),
reg = /^\w+#[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/;
for (var i = 0; i < emails.length; i++){
var em = emails[i];
var val = em.value || "";
if (!reg.test(val))
invalid.push(em);
em.className = em.className.replace(" invalid", "");
}
for (var i = 0; i < invalid.length; i++){
var inp = invalid[i];
var cls = inp.className.replace(" invalid", "");
inp.className = cls + " invalid";
}
}
Note that the could be made less verbose, but I opted for readability. The concept is, get each item with the class name we're validating against, iterate over them, and then mark it as invalid if it doesn't pass validation.

Related

html form 2 fields unique values required

I have a html form which has around 10 fields. 2 of those fields must have unique values.
So if I've got:
Name
Date of Birth
Email Address
Current City
Phone Number
Favourite City << Must be unique compared to City Born
City Born << Must be unique compared to Favourite City
Favourite Colour
Favourite Flower
Favourite Animal
I've found the below for validation, but that applies to all form fields. I just need to apply the 'unique' requirement to these two fields...it'd be okay for 'Favourite City' and 'Current City' to have the same values.
Thanks.
var frm = document.querySelector('form.classesName');
var inputs = frm.querySelectorAll('input[type=text]');
frm.addEventListener('submit', function(e) {
e.preventDefault();
var classArr = [];
for(var i = 0; i < inputs.length; i++) {
if(classArr.indexOf(inputs[i].value) != -1) {
inputs[i].style.backgroundColor = "red";
return false;
}
else
classArr.push(inputs[i].value);
}
frm.submit();
});
for(var j = 0; j < inputs.length; j++) {
inputs[j].addEventListener('focus', function() {
this.style.backgroundColor = "white";
});
}
https://jsfiddle.net/samuraii/70nkhthc/
Going off of the JavaScript you posted, and making some assumptions regarding the HTML make up of your form, would something like this work out?
var frm = document.querySelector('form.classesName');
frm.addEventListener('submit', function(e) {
e.preventDefault();
var favoriteCity = document.querySelector('input[name="favoriteCity"]');
var cityBorn = document.querySelector('input[name="cityBorn"]');
if ( favoriteCity.value === cityBorn.value ) {
alert("The City Where One Was Born Can't Be Their Favorite City... ?");
return false;
}
frm.submit();
});
<form class='classesName'>
<input type='text' name='favoriteCity' placeholder='Favorite City'>
<input type='text' name='cityBorn' placeholder='City Born'>
<input type='submit' value'Submit Form'>
</form>

Initializing javascript variables for repeating section in form

I have a form with a repeating section that uses jQuery to clone the section and increment the ids. Now I need to initialize the variables in order to send the form via PHP.
HTML:
<div class="repeatingSection">
<label for="poste_1">Poste :</label>
<input type="text" name="poste_1" id="poste_1"/>
<label for="date_1">Date :</label>
<input type="text" name="date_1" id="date_1"/>
</div>
JQUERY:
jQuery('.cloneButton').click(function(event){
event.preventDefault();
var currentCount = jQuery('.repeatingSection').length;
var newCount = currentCount+1;
var lastRepeatingGroup = jQuery('.repeatingSection').last();
var newSection = lastRepeatingGroup.clone(false).find('.cloneButton').remove().end();
newSection.insertAfter(lastRepeatingGroup);
newSection.find("input").each(function (index, input) {
input.id = input.id.replace("_" + currentCount, "_" + newCount);
input.name = input.name.replace("_" + currentCount, "_" + newCount);
});
newSection.find("label").each(function (index, label) {
var l = jQuery(label);
l.attr('for', l.attr('for').replace("_" + currentCount, "_" + newCount));
});
return false;
});
jQuery(document.body).on('click','.removeButton', function(){
jQuery(this).closest('div.repeatingSection').remove();
return false;
});
PHP :
$poste1 = '';
$date1 = '';
$poste1 = trim($_POST['poste_1']);
$date1 = trim($_POST['date_1']);
I know I would need to put them in an array and loop through them but I'm not sure how to go about it.
You can use a for loop and a count variable from javascript and do something like :
for($i=1; $i<$currentCount; $i++) {
${"poste".$i} = trim($_POST["poste_$i"]);
${"date".$i} = trim($_POST["date_$i"]);
}
You would have variables $poste1 and $date1. Using ${''} creates dynamic variables.

grab query string using javascript [duplicate]

This question already has answers here:
How can I get query string values in JavaScript?
(73 answers)
Closed 8 years ago.
i have a the following url
http://www.test.com/index.html?num1=123&num2=321
Now i want to grab the values of num1 and num2 using javascript
var QueryString = function () {
// This function is anonymous, is executed immediately and
// the return value is assigned to QueryString!
var query_string = {};
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
// If first entry with this name
if (typeof query_string[pair[0]] === "undefined") {
query_string[pair[0]] = pair[1];
// If second entry with this name
} else if (typeof query_string[pair[0]] === "string") {
var arr = [ query_string[pair[0]], pair[1] ];
query_string[pair[0]] = arr;
// If third or later entry with this name
} else {
query_string[pair[0]].push(pair[1]);
}
}
return query_string;
} ();
alert(QueryString.num1);
I feel like reaching the get parameters with javascript is kind of mixing up the roles of PHP and javascript so i prefer to do it this way. You can get the URL with window.href and parse but this is better form
Somewhere in PHP body:
echo '<input type="hidden" id="num1_arg" value=" . $_GET['num1'] . '/>';
echo '<input type="hidden" id="num2_arg" value=" . $_GET['num2'] . '/>';
Javascript (ill use jquery, but it can be done without)
n1 = $('#num1_arg').val();
n2 = $('#num2_arg').val();
Try using this simple function:
var parseQueryString = function() {
var queryString = window.location.search.substring(1);
var pairs = queryString.split("&");
var params = {};
for (var i = 0; i < pairs.length; i++) {
var parts = pairs[i].split("=");
var key = parts[0];
var value = parts[1];
params[key] = value;
}
return params;
};
If num1 and num2 are always in the same order, you can use regular expressions:
var url = ...
var pattern = /num1=(\d*)&num2=(\d*)/
var match = pattern.exec(url)
var num1 = match[1]
var num2 = match[2]

How to have two password fields controlled by one checkbox?

<form>
<fieldset>
Password: <span id="capsalert">CAPS LOCK = on</span><br>
<input type="password" id="pwd">
<script type="text/javascript">
document.write(
'<input type="checkbox" name="masking" onclick="unmask(this.checked)"> ' +
'Show the password as I type'
);
</script>
<br>
Password2:<br>
<input type="password" id="pwd2">
</fieldset>
</form>
<script type="text/javascript">
function chkCaps(e) {
ev = (e ? e : window.event);
kc = (ev.which ? ev.which : (ev.keyCode ? ev.keyCode : false));
sk = (ev.shiftKey ? ev.shiftKey : (ev.modifiers ? !!(ev.modifiers & 4) : false));
if(
(kc >= 97 && kc <= 122 && sk) ||
(kc >= 65 && kc <= 90 && !sk)
) {
document.getElementById('capsalert').style.display = 'inline';
}
else {
document.getElementById('capsalert').style.display = 'none';
}//end if
}//end function
function unmask(truefalse) {
oldElem = document.getElementById('pwd');
elem = document.createElement('input');
elem.setAttribute('type', (truefalse == true ? 'text' : 'password'));
elem.setAttribute('value', document.getElementById('pwd').value);
elem.id = 'pwd';
oldElem.parentNode.replaceChild(elem,oldElem);
document.getElementById('pwd').onkeypress = function(e) { chkCaps(e); };
}//end function
document.getElementById('pwd').onkeypress = function(e) { chkCaps(e); };
</script>
I'm using the above code in a slightly more complex form.
I have two separate "password" fields on the form. With the current code I can have the first password field show the characters as they are typed when the checkbox is ticked.
Also, the code notifies the user if they are typing with CAPS Lock enabled.
I would like to have both password fields exhibiting the same behavior rather than the first field only. Unfortunately, I do not know how to make that happen.
Thanks for the help.
EDIT:
A simple solution might be easier to find with the following code. I'm willing to use either one.
<script>
function changeType()
{
document.myform.pass.type=(document.myform.option.value=(document.myform.option.value==1)?'-1':'1')=='1'?'password':'text';
}
</script>
<body>
<form name="myform">
<input type="password" name="pass" />
<input type="password" name="pass2" />
<input type="checkbox" name="option" value='1' onchange="changeType()" />
</form>
</body>
Why don't you just change the type attribute of the password inputs in your unmask() function? That way it will be easier for you to manage more than 1 field. After checking whether you have to turn the input into a text one or a password one, do this:
// Suppose 'new_type' is either 'text' or 'password'
// and that 'pwd' and 'pwd2' are the id attributes for
// both of your password fields
document.getElementById('pwd').type = new_type;
document.getElementById('pwd2').type = new_type;
I suggest changing your approach a bit.
You could modify the client with no impact to the server code. For example, I would try using 2 input boxes with the same name. If you ever have one box visible while the other one has the 'disabled' HTML attribute set, the visible box will always be the only one submitted.
This way, your server-side code would only have to look for 1 input, under a single name.
jQuery caps lock test/function?
set both fields to class of password and:
jQuery('.password').caps(function(caps){
if(jQuery.browser.safari) return; // Safari already indicates caps lock
// "this" is current element
if(caps){
alert('Your caps lock is on!');
}else{
// no caps lock on
}
});
Try this:
function chkCaps(e) {
ev = (e ? e : window.event);
kc = (ev.which ? ev.which : (ev.keyCode ? ev.keyCode : false));
sk = (ev.shiftKey ? ev.shiftKey : (ev.modifiers ? !! (ev.modifiers & 4) : false));
if ((kc >= 97 && kc <= 122 && sk) || (kc >= 65 && kc <= 90 && !sk)) {
document.getElementById('capsalert').style.display = 'inline';
} else {
document.getElementById('capsalert').style.display = 'none';
}
//end if
}
//end function
function unmask(truefalse) {
for (var f in new Array('pwd', 'pwd2')) {
oldElem = document.getElementById(f);
elem = document.createElement('input');
elem.setAttribute('type', (truefalse == true ? 'text' : 'password'));
elem.setAttribute('value', document.getElementById(f).value);
elem.id = f;
oldElem.parentNode.replaceChild(elem, oldElem);
document.getElementById(f).onkeypress = function (e) {
chkCaps(e);
};
}
}
//end function
document.getElementById('pwd').onkeypress = function (e) {
chkCaps(e);
};
document.getElementById('pwd2').onkeypress = function (e) {
chkCaps(e);
};
What this does is make it so your code works on pwd and pwd2 by repeating it for each element in the array new Array('pwd', 'pwd2').
Most of the answers didn't work. One or two I left untried because they meant greater changes to my code than I wanted. I ended up finding yet another method to reveal the passwords: "Show password as text" control
I adapted the method there to my multiple password fields scenario:
<input type="checkbox" onchange="document.getElementById('gpwd').type = this.checked ? 'text' : 'password'; document.getElementById('pwd1').type = this.checked ? 'text' : 'password'; document.getElementById('pwd2').type = this.checked ? 'text' : 'password'"> Reveal passwords

Form Inputs updated via JS don't get submitted

The invoice input values which hold the totals of invoice line items that get updated via JS return a NULL value when they are submitted.
<span class="sublabel">Subtotal</span><input type="text" class="total-box" id="product-subtotal" readonly="true" />
<span class="sublabel">Tax</span><input type="text" class="total-box" id="product-tax" readonly="true" />
<span class="sublabel">Total</span><input type="text" class="total-box" id="order-total" readonly="true" />
The JS
function calcProdSubTotal() {
var prodSubTotal = 0;
$(".row-total-input").each(function(){
var valString = $(this).val() || 0;
prodSubTotal += parseInt(valString);
});
$("#product-subtotal").val(prodSubTotal);
};
function calcTaxTotal() {
var taxTotal = 0;
//var taxAmount = 10;
var taxAmount = $("#salesTaxAmount").val() || 0;
var productSubtotal = $("#product-subtotal").val() || 0;
var taxTotal = parseInt(productSubtotal) * parseInt(taxAmount) / 100;
var taxTotalNice = taxTotal;
$("#product-tax").val(taxTotalNice);
};
function calcOrderTotal() {
var orderTotal = 0;
var productSubtotal = $("#product-subtotal").val() || 0;
var productTax = $("#product-tax").val() || 0;
var orderTotal = parseInt(productSubtotal) + parseInt(productTax);
var orderTotalNice = "$" + orderTotal;
$("#order-total").val(orderTotalNice);
};
$(function(){
$('.row-total-input').each(
function( intIndex ){
$('.invAmount').livequery('blur', function() {
var $this = $(this);
var amount = $this.val();
var qty = $this.parent().find('.invQty').val();
if ( (IsNumeric(amount)) && (amount != '') ) {
var rowTotal = qty * amount;
$this.css("background-color", "white").parent().find(".row-total-input").val(rowTotal);
} else {
$this.css("background-color", "#ffdcdc");
};
calcProdSubTotal();
calcTaxTotal()
calcOrderTotal();
});
}
);
});
I originally had the inputs set as disabled however I have changed them to readonly because disabled fields can't be submitted.
What am i missing?
Thanks in advance.
You haven't set a name-attribute on your <input />s, so PHP can't access their values, and returns nothing when you look for $_POST['product-tax']. If you have set error_reporting to E_ALL, you should see a notice telling you you are trying to access an undefined index on the $_POST array.

Categories