I have the following form:
<form name="survey1" action="add5up.php" method="post" onsubmit="return validateForm()">
<div id="question">Q1) My programme meets my expectations</div><br />
Always<INPUT TYPE = 'Radio' Name ='q1' value= 'a'>
Usually<INPUT TYPE = 'Radio' Name ='q1' value= 'b'>
Rarely<INPUT TYPE = 'Radio' Name ='q1' value= 'c'>
Never<INPUT TYPE = 'Radio' Name ='q1' value= 'd'>
<input type="submit" value="addData" />
</form>
I am trying to validate whether a Radio button has been selected.
The code I am using:
<script type="text/javascript">
function validateForm()
{
if( document.forms["survey1"]["q1"].checked)
{
return true;
}
else
{
alert('Please answer all questions');
return false;
}
}
</script>
This is not working. Any ideas?
When using radiobuttons you have to go through to check if any of them is checked, because javascript threats them as an array:
<script type="text/javascript">
function validateRadio (radios)
{
for (i = 0; i < radios.length; ++ i)
{
if (radios [i].checked) return true;
}
return false;
}
function validateForm()
{
if(validateRadio (document.forms["survey1"]["q1"]))
{
return true;
}
else
{
alert('Please answer all questions');
return false;
}
}
</script>
Regards
My solution for validation complex forms include radios.
Usage is simple, function return TRUE/FALSE after validation.
var rs_target is ID of form
scTo is my custom func to scroll to ID, you can use own function to show/scroll errors
scTo("#"+err_target);
Error box will be like
<div class="rq_message_box rq_message_box_firstname display-none">err message</div>
Validation
var validation = validateForm(rs_target);
if(validation == false){
return false;
}
Function
function validateForm(rs_target) {
var radio_arr = [];
var my_form = $("#"+rs_target);
my_form = my_form[0];
$(".rq_message_box").hide(); //clear all errors
//console.log(my_form);
var err = false;
var err_target = "";
for (key in my_form) {
//console.log("do");
if(!my_form[key]||my_form[key]==null||err){
break;
}
//console.log(my_form[key].name);
var x = my_form[key].value;
//console.log(x);
if(my_form[key].type == "radio"){
//console.log("radio");
if(radio_arr[my_form[key].name] != true){
radio_arr[my_form[key].name] = null;
}
if(my_form[key].checked){
radio_arr[my_form[key].name] = true;
}
}else{
if (x == null || x == "") {
//console.log(form[key].name.toString() + " must be filled out");
err = true;
err_target = my_form[key].name;
//return false;
}
}
}
//console.log(radio_arr);
var rad_err = false;
for (key in radio_arr) {
if(rad_err){
break;
}
var x = radio_arr[key];
if (x == null || x == "") {
//console.log("RADIO> "+key + " must be filled out");
rad_err = true;
err_target = key;
}
}
if(err || rad_err){
// some error stuff, for me show prepared error/help box with class [".rq_message_box_"+err_target] / err_target is name of input like [.rq_message_box_firsname]
$(".rq_message_box_"+err_target).show(); //show error message for input
scTo("#"+err_target); //scroll to - custom func
return false;
}else{
return true;
}
}
Related
I have a long form which is broken into sections, and I want to trigger validation via JavaScript only for a particular section. Either I would like to specify the div containing a set of required inputs to validate, or if that's not possible, then loop through a set of known inputs and validate each one in turn. I'm using Bootstrap v3 validation.
Any ideas on how to do this?
you can use this
<?php echo form_open("placead/addCredentials",array("name"=>'form1',"id"=>'formElement','content')); ?>
<div class="halfForm">
<label>First Name</label> <input type="text" name="fname" id="fname" class="formtextBox" value="<?php echo set_value('fname'); ?>">
<span><?php echo form_error('fname'); ?></span>
</div><!--halfForm-->
var errors = false;
$( "#formElement" ).on("submit",function(e) {
$('#formElement .my input, #formElement .my select').each(
function(index){
var input = $(this);
if( (input.attr('type')=='text'|| input.attr('type')=='password') && input.attr('name')!='website' ){
if(input.val()==''){
$(this).parent('.halfForm').find('label').addClass('error');
input.focus();
errors = true;
return false;
}
else{
$(this).parent('.halfForm').find('label').removeClass('error');
errors = false;
}
}
if(input.attr('type')=='email'){
if(!ValidateEmail(input.val())){
$(this).parent('.halfForm').find('label').addClass('error');
input.focus();
errors = true;
return false;
}else{
$(this).parent('.halfForm').find('label').removeClass('error');
errors = false;
}
}
if(input.attr('type')=='tel'){
if(input.val()==''){
$(this).parent('.halfForm').find('label').addClass('error');
input.focus();
errors = true;
return false;
}else{
$(this).parent('.halfForm').find('label').removeClass('error');
errors = false;
}
}
});
if(errors){
e.preventDefault();
return false;
}
});
function ValidateEmail(mail)
{
if(/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(mail))
{
return (true)
}
return (false)
}
I've implemented the following in the absence of a Bootstrap Validation solution:
function ValidateAllRequiredFieldsInDiv(divName) {
var valid = true;
var required = $('#' + divName + " :input").filter('[required]');
required.each(function (index, obj) {
var control = $(this);
if (IsControlValid(control)) {
control.removeClass('invalid');
} else {
control.addClass('invalid');
valid = false;
}
});
return valid;
}
function IsControlValid(control) {
var value = control.val();
if (control.is('input') || control.is('textarea')) {
return value != null && value != '';
} else if (control.is('select')) {
return value != null && value != '' && value > 0;
} else {
return true;
}
}
I have a form with inputs
Fist name
Last name
Password
Etc
Current my validation works one by one. I would like to integrate them into one pop up box.
Example currently:
All not filled up; upon submission it would pop up First name not filled. I want it to be First name not filled, last name not filled etc
function validateForm() {
var x = document.forms["myForm"]["firstname"].value;
if (x == null || x == "") {
alert("First Name must be filled out");
return false;
}
var x = document.forms["myForm"]["lastname"].value;
if (x == null || x == "") {
alert("Last Name must be filled out");
return false;
}
var status = false;
var emailRegEx = /^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
if (document.forms["myForm"]["email"].value.search(emailRegEx) == -1) {
alert("Please enter a valid email address.");
return false;
}
var status = false;
var paswordregex = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$/;
if (document.forms["myForm"]["password"].value.search(paswordregex) == -1) {
alert("Please enter a at least 8 alphanumeric characters");
return false;
}
var password = document.getElementById("password").value;
var confirmPassword = document.getElementById("confirmpassword").value;
if (password != confirmPassword) {
alert("Passwords do not match.");
return false;
}
var checkb = document.getElementById('checkboxid');
if (checkb.checked != true) {
alert('Agree to privacy agreement must be checked');
} else {
status = true;
}
return status;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
function validateForm() {
var regexEmail = /^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
var regexMinThree = /^[A-Za-z0-9_ ]{3,13}$/;
var userFirstName = $.trim($('.firstName').val());
var userLastName = $.trim($('.lastName').val());
var userEmail = $.trim($('.email').val());
var userPassword = $.trim($('.password').val());
var msg = '';
if(!regexMinThree.test(userFirstName)) {
msg = 'FirstName, ';
} else {
msg = '';
}
if(!regexMinThree.test(userLastName)) {
msg = msg+'LastName, ';
} else {
msg = msg+'';
}
if(!regexEmail.test(userEmail)) {
msg = msg+'Email, ';
} else {
msg = msg+'';
}
if(!regexMinThree.test(userPassword)) {
msg = msg+'Password, ';
} else {
msg = msg+'';
}
if(!regexMinThree.test(userPassword) || !regexEmail.test(userEmail) || !regexMinThree.test(userLastName) || !regexMinThree.test(userFirstName)) {
msg = msg+'not filled correctly.';
alert(msg);
}
}
</script>
<form class="userRegistrationForm" onsubmit="return false;" method="post">
<input type="text" class="firstName" placeholder ="FirstName"/>
<input type="text" class="lastName" placeholder ="LastName"/>
<input type="email" class="email" placeholder ="Email"/>
<input type="password" class="password" placeholder ="Password"/>
<button type="submit" onclick="validateForm()" class="userRegistration">Submit</button>
</form>
Add a flag called error and a string called errorMessage, then in each if statement, if there is an error, make error = true and append error message.
Then when submitted, if error == true, alert errorMessage
You can add an <ul> in your html form where you want to show errors
Example
<ul class="errorContainer"></ul>
Then JS
function validateForm() {
var errors = "";
var x = document.forms["myForm"]["firstname"].value;
if (x == null || x == "") {
errors +="<li>First Name must be filled out</li>";
}
var x = document.forms["myForm"]["lastname"].value;
if (x == null || x == "") {
errors +="<li>Last Name must be filled out</li>";
}
var status = false;
var emailRegEx = /^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
if (document.forms["myForm"]["email"].value.search(emailRegEx) == -1) {
errors +="<li>Please enter a valid email address.</li>";
}
var status = false;
var paswordregex = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$/;
if (document.forms["myForm"]["password"].value.search(paswordregex) == -1) {
errors +="<li>Please enter a at least 8 alphanumeric characters</li>";
}
var password = document.getElementById("password").value;
var confirmPassword = document.getElementById("confirmpassword").value;
if (password != confirmPassword) {
errors +="<li>Passwords do not match.</li>";
}
var checkb = document.getElementById('checkboxid');
if (checkb.checked != true) {
errors +="<li>Agree to privacy agreement must be checked</li>";
}
if(errors!="")
{
$(".errorContainer").html(errors);
return false;
} else {
status = true;
return status;
}
}
I have a form myForm and I want to check if specific input field are filled out before sending the form. I'm very new to JavaScript so I don't really know what I did wrong. Any help is welcomed.
function validateForm() {
var validate = true;
var alert_string = "";
var children = $("#myForm").children("input");
console.log(children.size());
for(var i = 0; i < children.length ; i++){
if(children[i].attr(id).substring(0,8) != "ABC_FLAT"){
if(children[i].attr(id) == null || children[i].attr(id) == ""){
validate = false;
alert_string = alert_string.concat(childrern[i].attr(id)).concat(", ");
}
}
}
alert_string = alert_string.concat("must be filled out !");
if(validate == false){
alert(alert_string);
return false;
}
return true;
}
children[i].attr(id) == "" // wrong
You don't have to check whether their ids are null, you have to check whether their values are empty :)
if(children[i].value == "")
Since you are already using jQuery, you can simplify that code to a great extent. For example a simple "all fields filled" check can be
var flag=0;
$('#myForm').each(function() {
if ( $(this).val() === '' )
flag=1;
});
if you'll use jQuery, you can check the input fields if empty AND trap also white space/s. Add a class to all input fields , e.g. class="required" and add attribute fieldname with respective value for each input field.
var requiredFields = "";
$("#myForm").find('.required').each(function () {
if ($(this).val().trim().length == 0) {
requiredFields += " - " + $(this).attr("fieldname") + "\n";
}
});
if (requiredFields != "") {
alert("Please enter the following required field(s): \n" + requiredFields);
} else {
//save here
}
You can use required like <input required type="text" name="email" id="log" /> or use jQuery like
$("form").submit(function() {
var has_empty = false;
$(this).find('input').each(function() {
if(! $(this).val()) {
has_empty = true;
return false;
}
});
if(has_empty){return false;}
});
I am having trouble validation a form and staying on the same page. Below is my javascript validation which is working as i get popups.
function valueChecks(input){
var reqdFields = false;
var ncFields = false;
var catCheck = false;
var refCheck = false;
var dtCheck = false;
var retval = false;
reqdFields = checkRequiredFields(input) ;
ncFields = checkNonComplianceFields(input);
catCheck = checkCat();
refCheck = checkRef();
dtCheck = subDate();
var mesgNo="0";
if (reqdFields == true){
mesgNo="0";
} else { mesgNo="1";
}
if (catCheck == true){
mesgNo=mesgNo+"0";
} else { mesgNo=mesgNo+"2";
}
if (refCheck == true){
mesgNo=mesgNo+"0";
} else { mesgNo=mesgNo+"3";
}
if (dtCheck == true){
mesgNo=mesgNo+"0";
} else { mesgNo=mesgNo+"4";
}
if (ncFields == true){
mesgNo=mesgNo+"0";
} else {mesgNo=mesgNo+"5";
}
if (mesgNo =="00000"){
retval=true;
}
else if ((mesgNo =="10000")||(mesgNo =="12000")||(mesgNo =="12300")||(mesgNo =="12340")||(mesgNo =="12345")||(mesgNo =="10300")||(mesgNo =="10340")||(mesgNo =="10040")){
retval = false;
alert("Please check that you have filled in all the Mandatory Fields");
}
else if ((mesgNo =="02000")||(mesgNo =="02300")||(mesgNo =="02040")||(mesgNo =="02340")||(mesgNo =="02345")){
retval = false;
}
else if ((mesgNo =="00300")||(mesgNo =="00340")||(mesgNo =="00345")){
retval = false;
alert ("Please enter at least one Reference Value (File Number, STT or BL Number)");
}
else if ((mesgNo =="0004")||(mesgNo =="00045")){
retval = false;
alert ("The Incident Date must be less than or equal today's Date");
}
else if ((mesgNo =="0005")){
retval = false;
alert ("Please enter at least one Non Conforming Party");
}
return retval;
}
And this is how i declare my form.
<html:form action="/qaeditsrl" onsubmit="return valueChecks(this);" >
<input type=submit value="Submit" name="method" >
Can someone tell me why this is going wrong?
Try changing the submit button to input type=button.
Remove the onsubmit on the form, and add an id.
Then add onclick on the button doing all the checks,
if no errors were found use document.getElementById('formId').submit() for submitting;
pl. advise me how do i validate the array values in javascript.
i am posting the code that i am currently using. the problem is that even after filling up all the values, i still keep getting the validation error message.
pl. advise me where am i wrong
function chkdate() {
var x = document.forms["main"]["date"].value;
if (x == null || x == "") {
document.forms["main"]["date"].focus();
document.forms["main"]["date"].style.background = 'red';
alert("Date Cannot be empty");
return false;
}
}
function chkempty() {
var len = document.forms["main"]["item[]"].length;
if (len == undefined) {
var ic = document.forms["main"]["item[]"].value;
var iq = document.forms["main"]["qty[]"].value;
var ip = document.forms["main"]["price[]"].value;
if (ic == null || ic == "") {
document.forms["main"]["item[]"].focus();
document.forms["main"]["item[]"].style.background = 'red';
alert("Item Cannot be empty");
return false;
}
if (iq == null || iq == "") {
document.forms["main"]["qty[]"].focus();
document.forms["main"]["qty[]"].style.background = 'red';
alert("Qty Cannot be empty");
return false;
}
if (ip == null || ip == "") {
document.forms["main"]["price[]"].focus();
document.forms["main"]["price[]"].style.background = 'red';
alert("Price Cannot be empty");
return false;
}
} else for (i = 0; i < len; i++) {
var ica = document.forms["main"]["item[]"][i].value;
var iqa = document.forms["main"]["qty[]"][i].value;
var ipa = document.forms["main"]["price[]"][i].value;
if (ica == null || ica == "") {
document.forms["main"]["item[]"][i].focus();
document.forms["main"]["item[]"][i].style.background = 'red';
alert("Item Cannot be empty");
return false;
}
if (iqa == null || iqa == "") {
document.forms["main"]["qty[]"][i].focus();
document.forms["main"]["qty[]"][i].style.background = 'red';
alert("Qty Cannot be empty");
return false;
}
if (ipa == null || ipa == "") {
document.forms["main"]["price[]"][i].focus();
document.forms["main"]["price[]"][i].style.background = 'red';
alert("Price Cannot be empty");
return false;
}
}
}
other details are:-
form name: main
the input boxes item,qty and price are dynamic rows based on user's requirement.
thanks all.
I suggest you as first point to use JQuery in conjunction with validate plugin.
Then for your case follow this example that works fine for me:
$("#testform").validate({
rules: {'qty[]': {required: true,minlength: 1},
//other rules here
},
messages: {
'qty[]': "Select at least one qty",
//other custom error msgs go here
}
});
<input name="qty[]" id="1" value="1" type="checkbox" />
<input name="qty[]" id="2" value="2" type="checkbox" />
<input name="qty[]" id="3" value="3" type="checkbox" />
N.B. that the name of the field of array values must be specified with quotes ('qty[]')
or else you'll get a js error.