Trigger validation only on a div or on a field - javascript

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;
}
}

Related

How to validate input is required in jquery SmartWizard when content load from ajax?

i have success implemented jquery SmartWizard for validate input type text, but when input text load from ajax the validate is not working.
code to validate:
// Toolbar extra buttons
var btnFinish = $('<button></button>').text('Simpan')
.addClass('btn btn-info')
.on('click', function() {
if( !$(this).hasClass('disabled')) {
var elmForm = $("#myForm");
if(elmForm){
elmForm.validator('validate');
var elmErr = elmForm.find('.has-error');
if(elmErr && elmErr.length > 0) {
alert('Oops we still have error in the form');
return false;
} else {
alert('Great! we are ready to submit form');
elmForm.submit();
return false;
}
}
}
});
How do i validate the input?
i use this code, it work.
var btnFinish = $('<button></button>').text('Finish')
.addClass('btn btn-finish')
.on('click', function(){
if( !$(this).hasClass('disabled')){
var elmForm = $("#myForm");
if(elmForm){
elmForm.validator('validate');
var elmErr = elmForm.find('.has-error');
if(elmErr && elmErr.length >0){
alert('Oops, sorry');
return false;
} else {
alert('work! ');
elmForm.submit();
return false;
}
}
}
});

Check if input fields are filled out in a form

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;}
});

How to make an if argument on several inputs together?

I have been trying to make an if argument that will check if several inputs(that have the same class) have a value of negative number on several.
If one of them have, I want to have an error message.
I have been trying to do so, and I got the error message that I wanted but it continues to the next step eventhough I wrote return and event.preventDefault.
My Fiddle
My code below:
$("#inventoryForm").submit(function (event) {
$(".inventoryInput").each(function(){
if($(this).val() < 0) {
event.preventDefault();
$("#inventoryError").slideDown().text("blablabla");
;
return;
}
});
});
Your problem comes from the rest of your code. event.preventDefault() will not return out of the submit handler, it will just prevent the default form submit behavior.
Here's what you can do:
$("#inventoryForm").submit(function (event) {
var error = false;
//You seem to always want to prevent the default behavior
event.preventDefault();
$(".inventoryInput").each(function(){
if($(this).val() < 0) {
error = true; //Indicate there was an error
$("#inventoryError").slideDown().text("blablabla");
return false; //This stops the iteration
}
});
//Stop processing if there was an error
if (error) return;
$("#inventorySubmit").hide();
$("#inventoryChange").show();
$("#withdraw").show();
$(".inventoryInput").attr('disabled','disabled');
sum = 0;
/* var money = table.find("td:nth-child(2)");
for (var i = 0; i<money.length; i++) {
}
*/
});
Btw the code is even more consise without jQuery:
var inputs = [].slice.call(document.querySelectorAll('.inventoryInput'));
if (inputs.some(haveValueUnderZero)) {
//error
}
function haveValueUnderZero(input) { return input.value < 0; }
Try this:
<script>
$(".inventoryInput").each(function(){
var el = $(this)
$("#inventoryForm").on("submit", function (event) {
if(el.val() < 0) {
$("#inventoryError").slideDown().text("blablabla");
return false;
}
})
});
try a hidden verify function:
window.verify = function() {
var valid = true;
$('input').each(function() {
if ($(this).val() == "" || $(this).val() < 0) {
valid = false;
}
});
if (valid) {
$('#submit').click();
} else {
alert("Please complete all fields.");
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="inventoryForm">
<input type="text" placeholder="Product Id" name="prod_id" id="prod_id" />
<input type="number" placeholder="Quantity" name="quantity" id="quantity" />
<button type="button" onclick="verify()">Submit</button>
<button id="submit" type="submit" style="display:none"></button>
</form>
You can use a filter function to return only elements that do not match your condition.
var hasErrorElements = $('.inventoryInput').filter(function() {
return parseInt($(this).val()) < 0;
}).length > 0;
if (hasErrorElements) {
alert('Error!');
event.preventDefault();
return false;
}
Try this:
$("#inventoryForm").submit(function (event) {
event.preventDefault();
$(".inventoryInput").each(function () {
if ($(this).val() < 0) {
$("#inventoryError").slideDown().text("blablabla");
return false;
} else {
$("#inventorySubmit").hide();
$("#withdraw").show();
return true;
}
});
});
Also, you need to insert other functions like $("#withdraw").show(); inside the else statement.
JSFiddle Demo

Trying to Make Email Field Readonly/Disabled

I have a page that I need to disable the email field on. It needs to be readonly and dimmed. I've never worked with PHP before, and I assume that's what this code is, but, I'm not sure where I would disable the email field. Here's the code I have so far:
/**
* Validate our form fields
*/
var emailField, passwordField, confirmField, formfields = FormField.GetValues(%%GLOBAL_EditAccountAccountFormFieldID%%);
for (var i=0; i<formfields.length; i++) {
var rtn = FormField.Validate(formfields[i].field);
if (!rtn.status) {
alert(rtn.msg);
FormField.Focus(formfields[i].field);
return false;
}
if (formfields[i].privateId == 'EmailAddress') {
emailField = formfields[i];
} else if (formfields[i].privateId == 'Password') {
passwordField = formfields[i];
} else if (formfields[i].privateId == 'ConfirmPassword') {
confirmField = formfields[i];
}
}
if(emailField.value.indexOf("#") == -1 || emailField.value.indexOf(".") == -1) {
alert("%%LNG_AccountEnterValidEmail%%");
FormField.Focus(emailField.field);
return false;
}
if((passwordField.value != "" || confirmField.value != "") && (passwordField.value != confirmField.value)) {
alert("%%LNG_AccountPasswordsDontMatch%%");
FormField.Focus(confirmField.field);
return false;
}
return true;
}
%%GLOBAL_FormFieldRequiredJS%%
//]]>
To display a disabled texfield, you should output:
echo '<input type="email" name="name_of_field" value="email_to_display#gmail.com" disabled>';
Example:
See here (and have a look at the code):
Example
Perhaps if we had a link to the website we could have a look a it :)

Radio button validation through JavaScript

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;
}
}

Categories