JQuery validate triggered every time the browser gets the focus - javascript

I am using jquery validation plugin to validate my form. I have one field that I don't want to validate but in some way it is validated anyway and I get the error message "Please enter no more than 5 characters."
The field that is validated is a type=file field and I use it together with the Fynework jQuery MultiForm plugin. It's not validated when I try to submit the form, only when I chose file that has a name longer than 5 characters (I think, short names work long doesn't).
I have tried adding the class .ignore to the field that is validated and added that the ignore rule to my validat(), not difference in behaviour.
What can the problem be?
Here is my validat() method, I also include the point at which I add that method:
function addNewTicketValidation(){
$("#newticketform").validate({
ignore: ".ignore",
errorContainer: "#messageBox1",
errorLabelContainer: "#messageBox1 ul",
wrapper: "li",
debug:true,
rules: {
title: "required",
description: "required"
},
messages: {
title: "Titel saknas",
description: "Beskrivning saknas"
}
});
}
$("#newticketmanu").live('click',function(event){
$("#adminarea").load("http://" + hostname + "/" + compdir + "/modules/core/newticket/newticket.php", function(){
$('#my_file_element').MultiFile();
addNewTicketValidation();
});
});
My form:
<form method="post" enctype="multipart/form-data" id="newticketform" class="MultiFile-intercepted" novalidate="novalidate">
<input type="hidden" value="2000000" name="MAX_FILE_SIZE">
<label for="title">Rubrik</label> <input type="text" name="title" id="title"><br><br>
<label for="description">Beskrivning</label> <textarea name="description" id="description" cols="50" rows="15"></textarea><br>
<div id="my_file_element_wrap" class="MultiFile-wrap"><input type="file" maxlength="5" name="file[]" id="my_file_element" class="multi ignore MultiFile-applied" value=""><div id="my_file_element_wrap_list" class="MultiFile-list"></div></div>
<div id="files_list"></div>
<input type="submit" value="Upload" name="upload">
</form>
What can the problem be and how to fix it?
Thanks!

Remove the maxlength="5" attribute from the file input. This is read by the validation plugin and added as a rule (line 812 here https://github.com/jzaefferer/jquery-validation/blob/1.9.0/jquery.validate.js). Checking the specifications (http://www.blooberry.com/indexdot/html/tagpages/i/inputfile.htm), max length still means character length even on a file input, so if you want to limit the user to 5 file uploads you'll need some other method of achieving this.

Related

OnInvalid html event triggering after Required modifier removed through JS

I have three input fields I am attempting to enforce validity on. Currently, I have them all set as required, but removing the modifier with Javascript on submit if one of them is filled out; essentially, one must fill out at least one, but not none of these fields.
Here is an example of the fields:
jQuery(function ($) {
var $inputs = $('input[name=Input1],input[name=Input2], input[name=Input3]');
$inputs.on('input', function () {
// Set the required property of the other input to false if this input is not empty.
$inputs.not(this).prop('required', $(this).val().length > 0 && $(this).val() != 0)
});
});
jQuery(function ($) {
$("#Input1, #Input2").oninvalid = (function() {
$(this).setCustomValidity("Please enter a valid Input1, Input2, or Input3")
});
});
var Input3default = document.getElementById('Input3')
if (Input3.value.length == 0) Input3.value = "0";
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="input-group mb-3">
<form action="" method="get" autocomplete="off">
<div class="row" style="text-align:justify; width: 100%; display:inline">
<div class="">
<label for="text3">Input1:</label>
<input type="text" id="Input1" name="Input1" required oninvalid="this.setCustomValidity('Please enter a valid Input1, Input2, or Input3')" />
</div>
<div class="">
<label for="text4">Input2:</label>
<input type="text" id="Input2" name="Input2" required oninvalid="this.setCustomValidity('Please enter a valid Input1, Input2, or Input3')"/>
</div>
<div class="">
<label for="text5">Input3:</label>
<input type="text" id="Input3" name="Input3" required placeholder="0" pattern="[0-9]*" onsubmit="Input3default" oninvalid="this.setCustomValidity('Please enter a valid Input3')"/>
</div>
</div>
<p>
<input type="submit" value=" Submit " />
</p>
</form>
</div>
</div>
This seems to work fine if I leave it default; I have Input1 and Input2 empty by default, and Input3 has a value of "0" by default. If I enter Input1 or Input2, my submission goes through just fine. However, the problems begin if I alter Input3.
Problem 1: Any time I enter Inputs 1 and 2 but leave 3 blank, it triggers invalidity; my Input3default never seems to trigger, and it is passed blank and caught by the oninvalid tag.
Problem 2: Along with that, if I do not specify an Input2 along with my Input1 while Input3 is blank, it triggers invalidity on Input2. Using Chrome Debugger, I can see that the Required tag is removed, but my OnInvalid pop-up still comes up no matter what is remedied.
Essentially, I am trying to solve the second problem: When I remove the required html tag from my input, after invalidating another input with a Javascript-enforced default, my inputs refuse to validate on the front end.
I appreciate any advice and conjecture as to why this may be the case, and believe that the two problems are connected.
EDIT: Upon adding an = to my original oninvalid JQuery function, I removed a JS error. It appears that my Input3 default function triggers on pageload, but not on submit; I added an onsubmit function to input3, but am still receiving oninvalid events for input2.
I was able to fix this issue on my own, using the OnInput event.
The setCustomValidity function, when triggered, does not allow a submission while a CustomValidity is set. In order to fix this, I edited my inputs as so:
<input type="text" id="Input1" name="Input1" required oninvalid="this.setCustomValidity('Please enter a valid Input1, Input2, or Input3')" oninput="this.setCustomValidity('')"/>
I still have a few kinks to iron out, but this fixed my main problem in that the validity of an input was not being reset.
I'll leave this answer unaccepted at first to allow others to pitch in.

jQuery Validate seems to pass invalid form to submitHandler

I am trying to use jQuery Validate to prevent my ajax form submit when three fields contain any characters other than digits. Apparently I'm doing something wrong, but I can't see what.
EDIT: There seem to be two errors. My validation rules use the field ID instead of the field name. However, after fixing that problem, the form still validates unexpectedly..
This is my jQuery code:
(function() {
$(document).ready(function() {
formSubmits();
/**
* Handles all the form submits that go on.
* This is primarily the ID search and the form submit.
*/
function formSubmits() {
/*** SAVE RECIPE ***/
// validate form
$("#category-editor").validate({
rules: {
"time-prep": {number: true}, /* not sure why validation doesn't work.. */
"time-total": {number: true}, /* according to this, it should: http://goo.gl/9z2odC */
"quantity-servings": {number: true}
},
submitHandler: function(form) {
// submit changes
$.getJSON("setRecipe.php", $(form).serialize() )
.done(function(data) {
// de-empahaize submit button
$('.footer input[type=submit]')
.removeClass('btn-primary')
.addClass('btn-default');
});
// prevent http submit
return false;
}
});
}
});
})(jQuery);
Here's what I see in the inspector when I put a breakpoint inside the submitHandler. It is getting to the submitHandler despite bad input (a value of 'dsdfd' instead of '123')
This is the relevant markup:
<form id="category-editor" class="form-inline" method="get">
....
<div class='form-group'>
<div>
<label for="time-prep">Prep time (min):</label>
<input value="" id="time-prep" name="activeTime" class="form-control min-calc jqValidateNum" data-calc-dest="time-prep-desc" type="number">
<input value="" id="time-prep-desc" name="activeTimeDesc" class="form-control subtle" type="text">
</div>
</div>
<div class='form-group'>
<div>
<label for="time-total">Total time (min):</label>
<input value="" id="time-total" name="totalTime" class="form-control min-calc jqValidateNum" data-calc-dest="time-total-desc" type="number">
<input value="" id="time-total-desc" name="totalTimeDesc" class="form-control subtle" type="text">
</div>
</div>
<div class='form-group'>
<div>
<label for="quantity-servings">Servings:</label>
<input value="" id="quantity-servings" name="servings" class="form-control jqValidateNum" type="number">
</div>
</div>
....
</form>
You've got your rules set up with the "id" values for the <input> elements instead of their "name" values. Should be:
rules: {
"activeTime": {number: true},
"totalTime": {number: true},
"servings": {number: true}
},
edit — now that you've fixed that, I think the problem is that the "value" properties of the input elements are empty, because you've declared them type=number. Firefox and Chrome let you type anything into the fields, but they won't have a non-empty value unless the fields really do contain numbers.
If you also mark the fields as required, then it works. fiddle

Dojo form validating specific items in form tag

I have a dojo form which uses the dojo form wizard. The form has one tag. Within the form tag is a dojo.wizard.Wizard. It is a requirement that the wizard be inside a form tag. Within the Wizard is several wizard panes.
On each wizard pane i have form fields. I am preforming validation by calling a method on the wizard pane passFunction. However for the dojo validation to work i must get the children elements on the form and call the validate method against the form. This validates the entire form.
This is not practical for what i want to do since the first pane has n form elements, the second pane has n elements. When the validate function is called from the passFunction on the first pane it validates elements on other panes which are inaccessible yet.
How can i specify items to be validated for the form? I would like to validate only items on the first pane then move to the second pane and validate only those items. Under is my code structure:
Jsp
<form data-dojo-type="dijit/form/Form" id="myForm" />
<div data-dojo-type="dojox.widget.Wizard" data-dojo-props="style: 'height:450px; width: 600px'">
<div dojoType="dojox.widget.WizardPane" id="page1" passFunction="validatePage1" >
<input data-dojo-type="dijit/form/ValidationTextBox" data-dojo-props="
regExp: '[\\w]+',
required: true,
invalidMessage: 'First Name Required !'" id="fnameTextBox" title="First Name" placeholder="Your First Name" />
<input data-dojo-type="dijit/form/ValidationTextBox" data-dojo-props="
regExp: '[\\w]+',
required: true,
invalidMessage: 'Last Name Required !'" id="lnameTextBox" title="Last Name" placeholder="Your Last Name" />
</div>
<div dojoType="dojox.widget.WizardPane" id="page2" passFunction="validatePage2" >
<input data-dojo-type="dijit/form/ValidationTextBox" data-dojo-props="
regExp: '[\\w]+',
required: true,
invalidMessage: 'Age Is Required !'" id="ageTextBox" title="Age" placeholder="Your Age" />
<input data-dojo-type="dijit/form/ValidationTextBox" data-dojo-props="
regExp: '[\\w]+',
required: true,
invalidMessage: 'Phone Number Required '" id="phoneTextBox" title="Phone" placeholder="Your Phone Number" />
</div>
</div>
</form>
In validatePage1 i would only like to validate surname and firstname fields and once that is completed when i move to the second page i would like to validate age and phone number. I am only checking for nulls presently.
Javascript
dojo.require("dijit/form/Form");
dojo.require("dijit/form/Button");
dojo.require("dijit/form/ValidationTextBox");
dojo.require("dijit/Tooltip");
function validatePage1(){
var myform = dijit.byId('myForm');
myform.connectChildren();
myform.validate();
}
We need to know what are the fields to be checked. So we can add a class to those fields for this purpose. Lets call it "chkThisField".
//a function to validate the given field
var highlight = function(widget){
if(!widget.validate) return true;
widget._hasBeenBlurred = true;
widget.validate();
};
var fields = dojo.query(".chkThisField");
//above line is to get array of all fields with the "chkThisField" class
fields.forEach(function(fld){
var widget = dijit.getEnclosingWidget(fld);
highlight(widget);
});
So now,with the help of class selector, we have successfully validated specific fields only.

data-bind multiple text boxes to display in one text box

I'm using a Kendo edit box that a user can enter the different parts of a SQL connection string (server name, database, user name and password). I also have a text box that will show the user the entire connection string as they type.
My question is how can I data-bind each of the four text boxes (server, database, user and password) to one text box as the user enters data into each one.
Also, the user requested seperate fields.
Thanks in advance,
Dan Plocica
Doing it using Kendo UI would be:
HTML:
<div id="form">
<label>Server : <input type="text" class="k-textbox" data-bind="value: server"></label><br/>
<label>Database : <input type="text" class="k-textbox" data-bind="value: db"></label><br/>
<label>User : <input type="text" class="k-textbox" data-bind="value: user"></label><br/>
<label>Password : <input type="password" class="k-textbox" data-bind="value: password"></label><br/>
<div id="connections" data-bind="text: connection"></div>
</div>
JavaScript:
$(document).ready(function () {
var model = kendo.observable({
server : "localhost:1521",
db : "database",
user : "scott",
password : "tiger",
connection: function () {
return this.get("user") + "/" +
this.get("password") + "#" +
this.get("server") + ":" +
this.get("db");
}
});
kendo.bind($("#form"), model);
});
In the HTML there are two parts:
The input files where I define each input to what field it is bound in my model.
A div where I found its text to connection function in my model that creates a string from the different values.
This is automatically updated and you can freely edit each input.
You might decorate the input as I did setting it's CSS class to k-textbox, that's optional. The only important thing is the data-bind="value : ...".
The JavaScript, is just create and Observable object with the fields and methods that we want.
Running example here: http://jsfiddle.net/OnaBai/xjNMf/
I will write solution using jQuery JavaScript library, and you should use jQuery because its much easier and easier to read and also to avoid errors in different browsers.
**HTML**
Server: <input type="text" id="server"/><br/>
Database: <input type="text" id="database"/><br/>
Username: <input type="text" id="username"/><br/>
Password: <input type="text" id="password"/><br/>
<br/>
Full CS: <input type="text" id="solution"/><br/>
JS
<script type="text/javascript">
var _template = 'Data Source=%server%;Initial Catalog=%db%;Persist Security Info=True;User ID=%user%;Password=%pass%';
$(document).ready(function(){
$('#server,#database,#username,#password').keyup(function(){ updateSolution();});
});
function updateSolution(){
var _t = _template.replace('%server%', $('#server').val()).replace('%db%', $('#database').val()).replace('%username%', $('#username').val()).replace('%pass%', $('#password').val());
$('#solution').val(_t);
};
</script>

customising behaviour of Jquery validate

I am using Jquery validate to provide feedback to a user and provide them updates on the validity of the details they enter in the form. But I am having trouble customising the behaviour Jquery validate creates.
I have a simple form like this:
<form id="form1">
<label for="input1" />
<input name="input1" />
<input type="submit" />
</form>
When the user enters invalid information I want Jquery validate to output something like this:
<form id="form1">
<label for="input1" />
<input name="input1" class="error"/><span class="errorIcon">Error</span>
<p class="errorText">Error message</p>
<input type="submit" />
</form>
When the user fills out the field with valid information I want Jquery validate to output:
<form id="form1">
<label for="input1" />
<input name="input1" /><span class="successIcon">Success</span>
<input type="submit" />
</form>
I have set up the required rules and custom validation messages so they fire fine but I am having trouble getting the behaviour described above.
I have this currently:
$('#form1').validate({
showErrors: function(errorMap, errorList) {
if (errorList < 1 ) {
$('span.errorIcon').remove();
$('p.errorText').remove();
$('input.error').removeClass('error');
$('select.error').removeClass('error');
return;
}
$.each(errorList, function(index, error) {
if ($(error.element).siblings('.errorText').length === 0 && $(error.element).siblings('.errorIcon').length === 0) {
$(error.element).next('p.errorText').remove();
$(error.element).addClass('error');
$(error.element).after(
$('<p/>')
.addClass('errorText')
.append(error.message)
);
$(error.element).after(
$('<span>There is an issue with this field</span>')
.addClass('errorIcon')
);
}
});
},
//rules and messages defined here
);
So the above doesn't achieve what I want need currently and it also feels like I might be over complicating this issue. I am fairly inexperienced with javascript and Jquery. Any guidance in getting this sorted would be appreciated.
Cheers
EDIT:
Here is a link to a jsfiddle: http://jsfiddle.net/WJ9Vt/4/ with the sample form.
Could also post you css file, or do a jsfiddle on it ? Because you errorIcon is probably not shown because <span> will not display something as long as it has no content or you set display:block; and a special height and width.

Categories

Resources