jQuery validation don't work after add and input - javascript

I've a form where I have rows to an table manually.
This row need and input (required) and have two select...
The problem is, if I add more than one row the submit validation for the table don't work for the second (and subsequent rows)...
Javascript code:
$('#classAdd').click(function(e){
e.preventDefault();
//trainingAction.addRow(schoolGroups[0].schoolGroupId, -1, '');
//add one line
$('#classes > tbody:last').append('<tr><td><input class="required datepicker classStartDate" name="classStartDate" /></td>'+
'<td><select class="classSchoolGroupId"></select></td>'+
'<td><select class="classSchoolId"></select></td>'+
'<td><i class="icon-remove"></i></td></tr>');
var last = $('#classes tr:last');
var csgi = last.find('.classSchoolGroupId');
var csi = last.find('.classSchoolId');
var input = last.find('.classStartDate');
//append values
trainingAction.appendArrayToSelect(csgi, schoolGroups, 'schoolGroupId', 'schoolGroupName', -1);
//append values
trainingAction.appendArrayToSelect(csi, schoolGroups[0].getSchools(), 'Value', 'Text', -1);
//add event
trainingAction.schoolGroupChange(csgi);
//rebind datepicker
helpers.bindDatepicker();
//rebind validators
$('form').validate();
$(input).rules('add', {
required: true
});
//rebind remove button
trainingAction.removeClass();
});
I try the code above like the suggested here (jQuery validate - group inputs with similar rules).
Another snippet that I try and don't work (based on this post jquery validation rules)
$('form').validate({
rules:{
classStartDate: {
required:true
}
}
});
Any suggestion to resolve this issue?
Thanks in advance!
EDIT:
jQuery version: 2.0

If you duplicate with the same name on the input only the first one is validated, you need to add the brackets to the name like this
<input class="required datepicker classStartDate" name="classStartDate[]" />
And the javascript
$('form').validate({
rules:{
"classStartDate[]": {
required:true
}
}
});
hope i can help in something

Related

Selectize form validation - find out if an option has been chosen?

I'm using selectize for my drop down menus and I'm trying to do form validation. Each of the menus has class .code_select, and I want to know if an option has been selected on all of them. My code should determine if something is selected, and if not add the ID of the dropdown to an array called empty_fields. However, my dropdowns are all ending up in the array whether they have a selected option or not. This is my code:
$(".code_select").each(function(){
if ($(this).find('option:selected').length === 0) {
empty_fields.push($(this).attr("id")+'-selectized');
submitForm=false;
}
});
An example of one of the inputs:
<div class='col-4'>
<input type='text' class='form-control code_select' id='5-tree-Betpap-stdCodeSelect' name='5-tree-Betpap-stdCode' aria-label='Tree Metric Field 5 Standard Code select'>
</div>
And my selectize initialization:
// initialize newCodes selectize control
newCodesSelect[index] = $(this).selectize({
valueField: 'id',
labelField: 'label',
create: false,
hideSelected: false,
options: listOptions[listType],
searchField: 'label',
placeholder: "Choose " + listType + " codes (type to search)",
maxItems: 1,
});
//This stores the selectize object to a variable
newCodesSelectize[index] = newCodesSelect[index][0].selectize;
How do I determine if the select is still on the "placeholder" when my placeholder has a variable?
Thank you!
OK, here is what worked for me. I had to use .selectize-control as the selector and find if any of the items have data-attribute=null.
$('#nextBtn').click(function() {
console.log("Next Button - adding hidden fields");
//remove any left over error formatting
$('.requiredField').removeClass('requiredField');
var fld_text="";
$('#error-messages').html(fld_text);
// validate form before submit
var empty_fields=[];
var submitForm=true;
$(".code_description").each(function(){
if ($(this).val()==="") {
empty_fields.push($(this).attr("id"));
submitForm=false;
}
});
$(".selectize-control").each(function(){
if ($(this).find(".item").attr('data-value') == null) {
empty_fields.push($(this).prev("input").attr("id")+'-selectized');
}
});
empty_fields.forEach(function(element) {
if (element!=="undefined-selectized") submitForm=false;
});
if (submitForm===true) {
$('#nextForm').submit();
}
else {
fld_text="<p>Review required fields</p>";
$('#error-messages').html(fld_text);
empty_fields.forEach(function(element) {
if (element!=="undefined-selectized") $("#"+element).addClass("requiredField");
});
}
});

input file type error validation not working using jquery

Currently working on input file error validation When i searched about the validation i have found jquery validation so i have started using it and again when i searched about how to validate the input file i have got some useful information from SO Based on that I have created error validation page for input file. With my current code I can able to upload pdf & Jpeg file and view the file but the validation was not happening if user click next button without uploading any file it should say you have 2 files missed if the user upload one file and he click next button it should say you have 1 file miss. I have tried giving required in the html input type field and tried giving required in jquery validation nothing was working.
Here is my jquery code
$(".attachForm").validate({
ignore: false,
onkeyup: false,
showErrors: function (errorMap, errorList) {
var errors = this.numberOfInvalids();
if (errors) {
var message = errors === 0 ? 'You missed 1 field. It has been highlighted' : 'You have missed ' + errors + ' fields. Please fill before submitted.';
$("#error_message").html(message);
$(".error_msge").show();
} else {
$(".error_msge").hide();
}
this.defaultShowErrors();
},
errorPlacement: function () {
return false;
},
highlight: function (element) {
if($('input').attr('type') == 'checkbox') {
} else {
$(element).addClass('errRed');
$(".file_ipt").addClass('errRed');
}
$(element).prevAll('label').find('span.required-star').addClass('text-error-red').removeClass('text-error-black');
},
unhighlight: function (element) {
if($('input').attr('type') == 'checkbox') {
} else {
$(element).removeClass('errRed');
$(".file_ipt").addClass('errRed');
}
$(element).prevAll('label').find('span.required-star').addClass('text-error-black').removeClass('text-error-red');
},rules: {
apt_code:"required",
apt_cer:"required",
checkfile:"required"
},
submitHandler: function (form) { // for demo
alert('valid form submitted'); // for demo
return false; // for demo
}
});
I tried changing the name in all field but no use
Here is the fiddle link for the detailed code
Kindly please suggest me. kindly guide as i am not getting any stuff :(
Thanks for looking the question.
You have to assign the unique name attribute to each <input type="file" class="checkfile">
<input type="file" class="checkfile" name="file_alpha">
<input type="file" class="checkfile" name="file_beta">
and then in rules you have to define both fields and make sure they are required
rules: {
file_alpha: {
checkfile: "required",
required: true,
},
file_beta: {
checkfile: "required",
required: true,
}
},
Fiddle
Correct Solution
Above solution will work because assigning the unique name and required rules set will trigger the validation but will not return the desired result because OP trying to validate the input with same name attribute and triggering the error counter according to number of invalid input fields.
Reason the validation not working in original code because no required rules
rules: {
checkfile:"required"
},
defined anywhere.
so work around is set required rules and add to inputs with same name attribute OR type using jQuery each() function
$("input[type=file]").each(function() {
$(this).rules("add", {
required: true,
});
});
and validation will work, errors will triggered with counter and on validating the input field, error counter decrease as like OP's desired output.
Fiddle Proper Working Example

Validate dynamically generated form with jQuery Validator

Sorry for keep asking this, but I just can't figure it out. I've reduced the question to just the bare minimum.
How can I validate a dynamically generated form? Below is my attempt, but as seen, it shows up as passing validation.
https://jsfiddle.net/j2pgobze/1/
<form id="myForm">
<input type="text" name="email" id="email" value="bademail" >
</form>
<button id="validate">validate</button>
var myValidateObj = {
rules: {
email: {
email: true
}
}
};
$(function () {
jQuery.validator.setDefaults({
debug: true,
success: "valid"
});
$('#validate').click(function () {
//Validate the traditional form
var validate1 = $('#myForm').validate(myValidateObj);
console.log('Option 1', $('#myForm'), $('#email'), $('#email').val(), validate1.element('#email'), $('#email').valid(), $('#myForm').valid());
//Validate dynamically created form
var input = $('<input />', {
type: 'text',
name: 'email',
value: 'bademail'
});
//input.prop('value', 'bademail');
var form = $('<form />').append(input);
var validate = form.validate(myValidateObj);
console.log('Option 2', form, input, $('#email').val(), validate.element(input), input.valid(), form.valid());
});
});
The button needs to be inside the form and be a type="submit" in order for the plugin to capture the click.
Do not put .validate() within a click handler (See item 1). It's only used to initialize the plugin on a form. Exception, below we are creating the new form within a click handler and then immediately calling .validate() on the new form.
With these two small changes, the validation on the static form is working: jsfiddle.net/j2pgobze/3/
I rewrote your DOM manipulation code for clarity. I simply duplicated the HTML for the form and gave it a new ID: http://jsfiddle.net/zem84tfp/
$(function () {
// INITIALIZE plugin on the traditional form
var validate1 = $('#myForm').validate(myValidateObj);
$('#newform').one('click', function () {
// code here to create new form; give it new ID
// do not duplicate ID on anything else
// INITIALIZE plugin on the new form
var validate = $('#myForm2').validate(myValidateObj);
});
});

remove hidden field based on hidden field value using jquery

i would like to remove a hidden field from the form using jquery based on hidden field value.
please look the below html:
<input type="hidden" name="myvalue[]" value="value1"/>
<input type="hidden" name="myvalue[]" value="value2"/>
<input type="hidden" name="myvalue[]" value="value3"/>
i have jquery function which returns me the above value example:
$('#getValue').click(function(){
.... processing code here.....
return valueOfHiddenField;
});
now i would like to remove the hidden field from the form based on the value return by the getValue
so if the method returns me value1 then any input hidden field in the form with value as value1 should be removed. in this case the first input field of my html above.
any help or suggestion would be a great help ... thanks in advance
$('input[type="hidden"][value="+YOUR_VALUEVAR+"]').remove();
fiddle: http://jsfiddle.net/9tsgy/
You can iterate over input:hidden elements to check values and remove() based on value,
$("input:hidden").each(function () {
if (this.value == "value1") { // your condition here
$(this).remove()
}
}
$('#getValue').click(function () {
$(document).find("input[type=hidden]").each(function () {
if ($(this).value == 'Your Value') {
$(this).remove();
}
});
return valueOfHiddenField;
});
You can also do like this:
let hiddenValue = $(this).val();
$('input[type="hidden"][value="'+hiddenValue+'"]').remove();
Get the value of a hidden field and then use it dynamically and remove specific <input type="hidden">

Validate TextBox In JavaScript

i need a validate textbox which is accepted like this $250.00 here is '$' will accepted only one time and then never accepted '$' as well as '.'(dot).
You could use a masked input for example
your mask would be
$('#input').mask('$9?.99');
You can do:
var x = document.getElementById('your-text-box').value;
if(x.match(/^\$[0-9]+\.[0-9]+$/) == null) {
// invalid
}
else {
// valid
}
The regex /^\$[0-9]+\.[0-9]+$/ will match any string meeting the following constraints
Should start with a $
Should have 1 or more numbers after the $
Should have a . after the first set of numbers
Should end with 1 or more numbers after the .
Is jquery an option?
Here is a jquery solution. First of all I wouldn't validate expecting user to put '$'. I would put that outside the form and just allow people to enter the amount. That's weird, but I guess I don't really have the context on what you are doing. See Jquery validation:
$("#myform").validate({
rules: {
field: {
required: true,
digits: true
}
}
});
This is using digits to allow only numbers. Otherwise if you really need $ in there you need to create a custom validation rule.
<!-- wherever your jquery file is -->
<script src="../../jquery.min.js"></script>
<input type="text" id="cost"><input type="button" id="check" value="Check!">
<script>
// jquery solution
$(document).ready( function (){
$('#check').click( function (){
var cost = $('#cost').val();
var patt=/^(\$)?\d+(\.\d+)?$/;
var result=patt.test(cost);
alert(result);
});
});
</script>
Of course you can use pure java script as well to reduce the dependency
<input type="text" id="cost">
<input type="button" id="check" value="Check!" onClick="check();">
<script>
// Pure Javascript Solution
var check = function (){
var cost = document.getElementById('cost').value;
var patt=/^(\$)?\d+(\.\d+)?$/;
var result=patt.test(cost);
alert(result);
}
</script>

Categories