Input type text array jquery validation - php

I am new to php and jquery. I want validation for input type text.
<input type="text" size="5" name="add_qnty[]" value="">
I have tried the server side scripting but no use. So please help me
so that my submit will redirect only if all textboxes will fill with data.

Try this:
Add 'class=required' to all the required fields in the form and send these fields as an array to the below function like:
checkFrmFill( $( "#formid").find(".required"));
and the function will be:
function checkFrmFill(inputs) {
var returnVal = true;
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].type == "text" && inputs[i].value == "") {
returnVal = false;
} else if (inputs[i].tagName == "SELECT" && ( inputs[i].value == "select" || inputs[i].value == 0 ) || inputs[i].value == "" || inputs[i].value == null) {
returnVal = false;
} else if (inputs[i].type == "password" && inputs[i].value == "") {
returnVal = false;
} else if (inputs[i].type == "textarea" && inputs[i].value == "") {
returnVal = false;
}
}
return returnVal;
}
This will return false for those fields that are blank.

For every text input add required attribute at the end of the tag.
<input type="text" size="5" name="add_qnty[]" value="" required>
<input type="text" size="5" name="add_qnty[]" value="" required>
refer http://www.w3schools.com/tags/att_input_required.asp

HTML
...........................
form id ='frm'
submit button id ='submit_frm'
SCRIPT
.............................
$(function(){
$('#submit_frm').click(function(){
$('#frm').find('em.err').remove();
$('#frm').find('input[type=text]').each(function(){
if($(this).val()==''){
$(this).parent().append('<em class="err">This field is required</em>');
}
});
if($('#frm').find('em.err').length > 0 ){
return false;
}else{
return true;
}
});
});

Try this: Working Example JSFIDDLE
$("form").on("submit",function(){
var len = $("input[name='add_qnty[]']").filter(function() {
return !this.value;
}).addClass("has-error").length;
alert(len);
if(len == 0){
return true; // Submit form
} else {
return false; // Validation failed
}
})

Related

IF OR Function in jQuery on a PHP site

Can anyone tell me what's wrong and how to fix this bit of code...
I am trying to bring up a message and not go to the next page, if the #send_country box has either nothing in it or says "Send From..." (as its the placeholder).
This is the bit of code I am having issues with:
if (country == '0' || country == "Send From...") {
error = 1;
jQuery('.msg').text("Please Select A Country.");
}
I think I have an issue with the OR function as it works without the || country == "Send From...".
<script>
jQuery(document).ready(function(){
jQuery('.submit').click(function() {
var error = 0;
var country = jQuery('#send_country').val();
var countrys = jQuery('#delv_country').val();
var idsa = jQuery('.size').val();
if (country == '0' || country == "Send From...") {
error = 1;
jQuery('.msg').text("Select A Country.");
}
if (countrys == '0') {
error = 1;
jQuery('.msg').text("Select A Country.");
}
if (error) {
return false;
} else {
return true;
}
});
});
</script>
if the #send_country box has either nothing in it or says "Send From..." (as its the placeholder).
The placeholder attribute is different than the value, you couldn't get the placeholder using .val(); instead you should use .prop('placeholder') :
var country_placeholder = jQuery('#send_country').prop('placeholder');
So the condition will be :
if (country == '0' || country_placeholder == "Send From...") {
But like this the condition will always return true since the placeholder will not change if you're filling the field, so i suggest just to check if the value is empty or '0' :
if (country == '0' || country == "") {
Hope this helps.
jQuery('.submit').click(function() {
var error = 0;
var country = jQuery('#send_country option:selected').val();
if (country == '') {
error = 1;
jQuery('.msg').text("Select A Country.");
}
if (error) {
console.log('EROOR');
} else {
console.log('SUBMIT');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<select type="text" id='send_country'>
<option value="" disabled selected>Send From...</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
<button class='submit'>Submit</button>
</form>
<span class='msg'></span>

sending variable in php to ajax function

How can i push variable to ajax function in php file (witch refers to ajax )
if i have $v in my php . if all is ok it's echo "ok" in php file .So what should i do next
if ($_POST){
for ($j=0; $j< count($row);$j++){
mysql_query("INSERT INTO `".PREFIX_USR."delivery_address` (`id_personl_data`,`country`,`province`,`city`,`street`,`house`,`apartment`)
VALUES ( '12','".$row[$j][0]."','".$row[$j][1]."','".$row[$j][2]."','".$row[$j][3]."','".$row[$j][4]."','".$row[$j][5]."') ");
var count = query['id']; // just an example of what i need to push
}
echo "ok";
}
js
(function(){
function changeData(){
var name = d.getElementById('new_name').value,
surname = d.getElementById('new_surname').value,
email = d.getElementById('new_email').value,
telephone = d.getElementById('new_phone').value,
robot = d.getElementById('spam_change').value,
xml = eventsObj.getXmlHttp();
var arr = [].map.call(document.querySelectorAll('.parent_clone'), function(block) {
return [].map.call(block.querySelectorAll('.left_info_address'), function(inp) {
return inp.value;
});
});
for (var i = 0; i<arr.length-1;i++){
arr[i].push('/');
}
console.log(arr);
if(name === "" || surname === "" || email === "" || (telephone === "")){
alert("fill the fields");
}
else {
xml.open("POST",path_ajax_files+"edit_personal_data.php",true);
xml.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xml.send("name="+encodeURIComponent(name)+
"&surname="+encodeURIComponent(surname)+
"&email="+encodeURIComponent(email)+
"&telephone="+encodeURIComponent(telephone)+
"&robot="+encodeURIComponent(robot)+
"&arr="+encodeURI(arr));
xml.onreadystatechange = function(){
if(xml.readyState === 4){
if(xml.status === 200){
if(xml.responseText !== ""){
alert(xml.responseText);
if(xml.responseText === "ok"){
alert("data will be changed");
}
} else {
alert('try again later');
}
}
}
};
}
}
eventsObj.addEvent(saveData, "click", changeData, false);
})();

JS form validation not working

I'm trying to validate some form fields using JS functions, but they don't seem to load or check the field when the submit button is clicked.
<html>
<body>
<?php require_once('logic.php'); ?>
<h1>Add new Region/Entity</h1>
<?php
if ($_POST['submitted']==1) {
echo $error;
}
?>
<form action="logic.php" method="post" name="registration" onSubmit="return formValidation();">
Region: <input type="text" name="region" value="<?php echo #$_POST['region']; ?>"><br>
Description: <br><textarea name="description" cols="50" rows="10"><?php echo #$_POST['description']; ?></textarea><br>
Remarks: <input type="text" name="remarks" value="<?php echo #$_POST['remarks']; ?>">
<input type="hidden" name="submitted" value="1"><br>
<input type="submit" value="Submit" onclick="">
And here's the JS:
<script type="text/javascript">
function formValidation() {
var region = document.registration.region;
var descr = document.registration.description;
var remarks = document.registration.remarks;
if(empty_validation()) {
if(reg_validation()) {
if(reg_letters()) {
if (desc_letters()) {
if (desc_validation()) {
}
}
}
}
}
return false;
}
function empty_validation() {
var reg_len = region.value.length;
var descr_len = descr.value.length;
var rem_len = remarks.value.length;
if (reg_len == 0 || decr_len == 0 || rem_len == 0) {
alert("Please fill all the fields");
return false;
}
return true;
}
function reg_validation() {
if (reg_len > 50) {
alert("Only 50 characters are allowed in the Region field");
region.focus();
return false;
}
return true;
}
function reg_letters() {
var letters = /^[A-Za-z]+$/;
if(region.value.match(letters)) {
return true;
} else {
alert('Region field must have only alphabetical characters');
region.focus();
return false;
}
}
function desc_validation() {
if (descr_len > 500) {
alert("Only 500 characters are allowed in the description field");
descr.focus();
return false;
}
return true;
}
function desc_letters() {
var iChars = "!##$%^&*()+=-[]\\\';,./{}|\":<>?";
for (var i = 0; i < descr_len; i++) {
if (iChars.indexOf(descr.value.charAt(i)) != -1) {
alert ("Your description has special characters. \nThese are not allowed.\n Please remove them and try again.");
return false;
}
}
return true;
}
</script>
</form>
</body>
</html>
As you can see, I'm posting values from the form to a PHP file. And I've used the onSubmit event in the form tag to initialize the formValidation() function. It isn't working for some reason.
Here's a working example if you need one.
I'm not going to fix every little error you have, but the main problem is that variables aren't defined where you expect them to be. You can't declare a variable in one function and expect it to be available in the next (without passing it as a parameter or declaring it globally). For example, your empty_validation function should be this:
function empty_validation(region, descr, remarks) {
var reg_len = region.value.length;
var descr_len = descr.value.length;
var rem_len = remarks.value.length;
if (reg_len == 0 || decr_len == 0 || rem_len == 0) {
alert("Please fill all the fields");
return false;
}
return true;
}
And in your formValidation function, you call it like this:
if(empty_validation(region, descr, remarks)) {
This is just one example, and you would need to do it in a few places.
A few other things - you always return false from formValidation...did you mean to put return true; inside the innermost if statement? Also, since all you seem to be doing is calling each of those functions, you can probably put them into one big if statement, like this:
if (empty_validation() && reg_validation() && reg_letters() && desc_letters() && desc_validation()) {
return true;
}
return false;

html form not working after putting exception

i've created exception using JS so that user are only allowed to input numbers to the html form field. this is working nicely but the problem is, the Submit button isn't working anymore. if i remove the exception code, submit button is working nicely! i can't understand where is the problem. anyone can help please? thanks in advance!
here is the exception:
function validateNum(evt) {
var theEvent = evt || window.event;
var key = theEvent.keyCode || theEvent.which;
key = String.fromCharCode( key );
var regex = /[0-9]|\./;
if( !regex.test(key) ) {
theEvent.returnValue = false;
if(theEvent.preventDefault) theEvent.preventDefault();
}
}
function validate()
{
if( document.myForm.ic.value == "" ||
isNaN( document.myForm.ic.value ) ||
document.myForm.ic.value.length != 12)
{
alert( "Please provide your correct IC Number!" );
document.myForm.ic.focus() ;
return false;
}else{
// Put extra check for data format
var ret = validateNum();
if( ret == false )
{
return false;
}
}
here is my html form action:
<form name="myForm" method="post" action="nonuum_reg.php" onsubmit="return(validate());">
and here is the input field & submit button:
<input name="ic" type="text" id="ic" maxlength="12" size="45" onkeypress='validateNum(event)'/>
<input type="submit" value="Apply" />
Try this one as my explanation on my comment on your question:
<form name="myForm" method="post" action="nonuum_reg.php" onsubmit="validate(event);">
<input name="ic" type="text" id="ic" maxlength="12" size="45" onkeypress='validateNum(event)'/>
<input type="submit" value="Apply" />
</form>
<script>
function validateNum(evt) {
var theEvent = evt;
var key = theEvent.keyCode || theEvent.which;
key = String.fromCharCode( key );
var regex = /[0-9]|\./;
if( !regex.test(key) ) {
theEvent.returnValue = false;
if(theEvent.preventDefault) theEvent.preventDefault();
}
}
function validate(evt){
if( document.myForm.ic.value == "" || isNaN( document.myForm.ic.value ) || document.myForm.ic.value.length != 12) {
evt.preventDefault();
alert( "Please provide your correct IC Number!" );
document.myForm.ic.focus() ;
return false;
}
}
</script>
You should still create validation on your PHP controller to prevent if users turn off javascript on theirs browser.
Try adding a return true in you =r else close
...
else{
// Put extra check for data format
var ret = validateNum();
if( ret == false )
{
return false;
}
return true;
}
...
This should also help you (not the same issue but same code)link:

Javascript validation with php sample 1

I have a form with 4 fields
First Name (required)
Last Name (required)
Email (required)
phone (optional) (if user enter any it should validate to a number or not) below is the form i have
<form name="myForm" method="post" onsubmit="return validate();">
First Name : <input type="text" name="fname" id="id_fname"> <br>
Last Name : <input type="text" name="lname" id="id_lname"> <br>
Email : <input type="text" name="email" id="id_email"> <br>
Phone : <input type="text" name="phone" id="id_phone"> <br>
<input type="submit" value="send">
</form>
And below is the javascript code
<script type="text/javascript">
function validate()
{
if (document.myForm.id_fname.value == '') {
alert("Enter First Name");
return false;}
else if(document.myForm.id_lname.value == '') {
alert("Enter Last Name");
return false; }
// now here email validation is not working
else if(document.myForm.id_email.value == '' || document.myForm.id_email.value != ''){
var x = document.myForm.id_email.value;
var atpos=x.indexOf("#");
var dotpos=x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
alert("Not a valid e-mail address");
return false;
else
return true;
}
// this is for phone number, if this field is empty no validation, if this field not empty it should validate to contain only numbers
else if(document.myForm.id_phone != '') {
var ValidChars = "0123456789";
var IsNumber=true;
var Char;
sText = document.form1.testfield2_phone.value ;
for (i = 0; i < sText.length && IsNumber == true; i++)
{
Char = sText.charAt(i);
if (ValidChars.indexOf(Char) == -1)
{
IsNumber = false;
}
}
if(IsNumber == false)
alert("Enter valid Number");
return false;
else
return true;
}
else
return true;
document.myForm.submit();
}
</script>
Email validation and phone validation are not working when i comment these email and phone i get validation good for first name and last name... is there any error in code for validation.
And when a form is submitted, when we refresh then details are resubmitted again, how to avoid this.
Why do you do it so complicated???
if (document.myForm.id_fname.value.length < 3) {
alert("Enter First Name");
return false;
} else if (document.myForm.id_lname.value.length < 3) {
alert("Enter Last Name");
return false;
} else if (!/^\S+#\S+\.\w+$/.test(document.myForm.id_email.value)) {
alert("Not a valid e-mail address");
return false;
} else if (!/^\d+$/.test(document.myForm.id_phone.value)) {
alert("Enter valid Number");
return false;
}
return true;
There are multiple syntax errors, which are mainly related to the else if
For the resubmissions have alook at Post - Redirect - Get (PRG) is a common design pattern for web developers to help avoid certain duplicate form submissions and allow user agents to behave more intuitively with bookmarks and the refresh button.

Categories