I have a form with AngularJS validation.
The problem is that I add input elements to this form using Jquery and AngularJS doesn't add those elements into the form's validation..
Here's an example: http://jsfiddle.net/ULEsy/
var input = $compile($('<input type="text" ng-model="textinput" required />'))($scope);
$("#someform").append(input);
In the example, even though the input field is not valid (empty - can be seen by the red border), the entire form is valid.
Any help?
#Ephi and I found a solution for this problem.
Apparently, you need to first append the element to the DOM, and only then use $compile. Also, the new element needs a name.
See here
angular.module("app", []).controller('someController', function($scope, $compile) {
$scope.add = function() {
var input = $('<input type="text" ng-model="textinput" name="x" required />');
$("#someform4").append(input);
$compile(input)($scope);
}
});
Related
I'm trying to impliment some CRUD page with AngularJS. So i have input with some validation requirements
<input ng-class="addForm.country.$error.pattern?'bad-input-border':''"
name="country"
ng-model="adding_element.country"
type="text"
pattern="[A-Za-z]+"
class="form-control">
Pattern that match only letters.
Also i have bingding model with that input.
The problem is: when i change input value directly on page, validation works fine addForm.country.$valid == true; but when i'm trying to change my model from code i get addForm.country.$valid == false even if data is valid.
I changing model on button click, that get generated element from my controller:
$scope.generate_country = function()
{
$http.get("/index.php/cars/generate").then(function(response){
$scope.adding_element.country = response.data.item.Country;
});
};
The result in response.data.item.Country is string. It fails input pattern when i click the button, but when i CTRL+C CTRL+V generated result in input it's OK.
How can i solve that? TIA!
I'm running into a strange issue in Firefox that I hope someone can explain to me. I have an AngularJS controller with a method that is tied to ng-change on a variety of input controls in a form, including one that is marked as a number input. The logic of this method is that if any one of the bound scope variables is set properly, to set another scope variable to true. This is basically an attempt at form validation where any one (or more) of the inputs is required.
Example:
app.controller('test', function($scope) {
$scope.num = 0;
$scope.name = "";
$scope.valid = false;
$scope.inputChange = function() {
console.log('Input changed');
$scope.valid = ($scope.num > 0) || ($scope.name.length > 0);
}
});
And form:
<form name="numberTest" ng-app="myApp" ng-controller="test">
<input ng-model="name" name="name" type="text" ng-change="inputChange()"/>
<input type="number" ng-model="num" name="n" id="n" ng-change="inputChange()"/>
<input type="button" value="Go" ng-disabled="!valid"/>
</form>
This all works fine in Chrome, but in Firefox this ng-change handler is fired when non-numeric text is entered in the numeric input and the textbox itself does get this bogus data in it although the model is not updated. This leads to a confusing state where there is invalid data in the num textbox that is not bound to the AngularJS model but the user can click the button. Chrome does not present this problem as it does not render the non-numeric data in the input control.
How can I detect (and handle) this scenario? The input control is displaying text that is invalid and not bound to the binding model.
I am certainly open to alternative implementations to achieve this same effect. AngularJS version is 1.3.0.
Example plunker to run in Firefox to see the "bad" behavior
I ended up discovering the $valid attribute of these number inputs, and that seemingly satisfies my needs:
Returns true if empty
Returns false if non-numeric data is in the control
So, my updated button:
<input type="button" value="Go" ng-disabled="!valid || !numberTest.n.$valid"/>
I am trying to create a form where the user might want to add two input fields dynamically, and this form is linked to the validate JQuery Plugin.
$('.addnote').on("click",function(){
countnotes++;
var newnote = $(".notes:first").clone();
newnote.find('input:file').val("");
newnote.find('input:text').val("");
var oldindexinput = countnotes-2;
var newindexinput = countnotes-1;
var attachement = newnote.find('#Justificatif'+oldindexinput+'Attachment');
attachement.attr('id','Justificatif'+newindexinput+'Attachment');
attachement.attr('name','data[Justificatif]['+newindexinput+'][attachment]');
var motif = newnote.find('#Justificatif'+oldindexinput+'Motif');
motif.attr('id','Justificatif'+newindexinput+'Motif');
motif.attr('name','data[Justificatif]['+newindexinput+'][motif]');
newnote.find('input:text[readonly]');
var firstnoteid = $(".notes:first").attr('id');
newnote.attr('id','notes'+countnotes);
newnote.attr('style','');
newnote.insertBefore('#'+firstnoteid).hide();
newnote.slideDown();
});
Here is the Html code
<input name="data[Justificatif][0][attachment]" type="text" readonly placeholder="Feuille de support" required>
<input name="data[Justificatif][0][motif]" placeholder="Motif de dépenses" class="input-medium" maxlength="255" type="text" id="Justificatif0Motif" required>
The problem with my code is that it clones the validation status as well with the new input fields, and I want to get rid of that.
Thank you
snapshot of the input fields cloned
Typically, during jquery validation, class='required' is applied to the elements which are validation during form submit.
Given, the elements you are cloning does have class='required' defined, you may simply remove it after cloning.
var newnote = $(".notes:first").clone();
newnote.removeClass('required');
Here's an example : http://jsfiddle.net/DinoMyte/TP768/268/
Some thoughts off the top of my head (based on a similar project I'm referencing):
Can you confirm that the id of the new input field is definitely unique. I see you calling "newnote.attr('id','notes'+countnotes);", but can you confirm the html is changed correctly?
If the id is unique, try unattaching and reattaching your validation engine. (In my code I kill everything and recreate my forms every time there's a change, then re-call jQuery($('form[name$="config_form"]')).validationEngine('attach');)
Angular validation currently works by updating on model change. Although displaying these validation errors upon keyup is not very UI friendly.
An ideal solution would be to display the error messages on blur, along with on form submit. Once an input is blurred on the first time and an error message is displayed, the input would then need to be updated on keyup/model change.
I have seen the following which allows the model to be updated upon blur, but this is not an ideal solution since the model is only updated on blur for every situation.
<input type="text" name="user" ng-model="user" ng-model-options="{ updateOn: 'blur' }" required>
I also came across the following solution that works well on blur and then changes to keyup after an error exists. Although the validation does not apply on form submit.
http://plnkr.co/edit/VSPOYO16ozq2bKaLl3n9?p=preview
Here for this you can have one angular scope variable which maintain the state of form submit is submitted or not by default that variable is false.
$scope.submitted = false;
and one scope function which validate the fields on form submit. Keep in mind place name attribute of form element is must be stetted and refereed same in function. Function approach is to make it generic. You can directly write into html template also by accessing $dirty and $error variable of that input elements.
$scope.validateInput = function (name, type) {
var input = $scope.demoform[name];
return (input.$dirty || $scope.submitted) && input.$error[type];
};
This is function which will be called on form submission.
$scope.submitForm = function () {
$scope.submitted = true;
if ($scope.demoform.$valid) {
console.log('Submitted!!');
} else {
console.log('Not valid!!');
return false;
}
};
Now on html template you can write this way .
<form name="demoform" ng-submit="submitForm()" novalidate="">
<input type="text" name="name" required="" ng-model="name"/>
<span ng-show="validateInput('name', 'required')" class="text-danger">Name is required</span>
<button type="submit" class="btn btn-info" >Save</button>
</form>
Now on form submit You can see the validation message is there if field is not valid.
Demo Plunkr of form validation on form submit in angular
Create a directive that is bound to the blur event, you seem to have found one that will work but I can't read the Plunkr on my phone, and use this to set validity.
Now inside your submit function in the controller you need to check the form for errors.
if (Object.keys($scope.formName.$error).length > 0) {
return false;
}
is an easy way to do this and will also still have the form set to $submitted.
I am attempting to use KendoUI Validator with an ASP.NET WebForms project.
I have a simple page, that has a number of inputs, and of course ASP.NET adds some hidden form elements as well.
I have the following questions:
Why does the KendoUI Validator not ignore hidden form fields, and how to I get it to?
Why does KendoUI apply the rules to every input field, and how to do get it to ignore some fields. I want a declarative way to do this, not by adding all sorts of exceptions in my validation rule, as per the example in the KendoUI Validator API page.
Shouldn't it be that if no rule is set as an attribute in the input element (eg; required) then no validation is applied?
Behavior I am getting:
With no validation specific attributes on the input element at all, the validation rules still get applied when I call .validate()
Hidden form elements are validated.
I am using the following kendo:
http://cdn.kendostatic.com/2013.2.716/js/jquery.min.js
http://cdn.kendostatic.com/2013.2.716/js/kendo.all.min.js
http://cdn.kendostatic.com/2013.2.716/styles/kendo.common.min.css
http://cdn.kendostatic.com/2013.2.716/styles/kendo.default.min.css
I have put together a fiddle that demonstrates this:
http://jsfiddle.net/codeowl/B5ML4/3/
And here is the code, for those that don't have access to fiddle:
I have the following markup:
<form action="/" id="testForm">
<input type="hidden" name="__EVENTTARGET" id="__EVENTTARGET" value="" />
<input type="hidden" name="__EVENTARGUMENT" id="__EVENTARGUMENT" value="" />
<input type="text" id="testInput" value="">
<a id="testValidate" href="javascript:;">Validate</a>
</form>
and the following script:
var validatable = $("#testForm").kendoValidator({
rules: {
testRule1: function (input) {
// Only "Tom" will be a valid value for the FirstName input
return input.is("[name=firstname]") && input.val() === "Tom";
},
testRule2: function (input) {
return $.trim(input.val()) !== "";
}
},
messages: {
testRule1: "Your name must be Test",
testRule2: "Your name must be Foo"
}
}).data("kendoValidator");
$("#testValidate").click(function () {
if (validatable.validate()) {
alert('passed');
}
});
and when I press the validate link it shows validation messages for the hidden fields.
For anyone interested, I did eventually get a response to this question. I had to post it on the KendoUI Premium Forums to get someone to respond.
Here is the response:
How do I get KendoUI Validator to ignore hidden form elements?
Indeed, the hidden input elements are passed through the validation
rules logic by default due to the fact that there are multiple widgets
which has a hidden input as part of there markup. However, as the
built-in rules relays on the presence of certain attributes, if there
are missing no validation will happen on the hidden inputs. Therefore,
your own custom rules should handle this scenario and skip the
appropriate elements. For example:
testRule2: function (input) {
if (!input.is(":hidden")) {
return $.trim(input.val()) !== "";
}
return true;
}
I'm writing this for new comers.
Simply make hidden inputs disabled
$('#hidden_input').prop('disabled', true) // won't check in kendo or standard jquery validation
$('#hidden_input').prop('disabled', false) // will check in kendo or standard jquery validation
validator._inputSelector=
":input:not(:button,[type=submit],[type=reset],[disabled],[readonly],[type=hidden],:hidden)
[data-validate!=false]
This will not validate hidden controls. Kendo 2018 version