Angular Validation not working when dot in model - javascript

Angular validation is working when there is no dot(.) in model in this following code...
<div class="form-group">
<label for="title">Post Title</label>
<input ng-model="new_title" class="form-control" name="new_title" type="text" required/>
<p class="error" ng-show="addForm.new_title.$touched && addForm.new_title.$invalid">This field is required</p>
</div>
But it is not working when I use ng-model="new.title" like in the following code...
<div class="form-group">
<label for="title">Post Title</label>
<input ng-model="new.title" class="form-control" name="new.title" type="text" required/>
<p class="error" ng-show="addForm.new_title.$touched && addForm.new.title.$invalid">This field is required</p>
</div>
Here is what I am using new in my controller
$scope.submit = function(){
var request = CRUD.create($scope.new);
request.success(function(response){
$scope.flash = response.status;
});
};
Help would be appreciated

You should not change your name along with your model.
<div class="form-group">
<label for="title">Post Title</label>
<input ng-model="new.title" class="form-control" name="new_title" type="text" required/>
<p class="error" ng-show="addForm.new_title.$touched && addForm.new_title.$invalid">This field is required</p>
</div>
This is how it should look like.
The validation doesn't check your model. It checks the form model that you bind the scope when using name attribute. So when checking for errors, you use the name attributes of the form and the inputs. You just need to change your name of the input from new.title to new_title.

You can't use dot (.) in variable name. you should use _ or camel-case to declare variable like:
new_title or newTitle
if want to use dot (.) notation then use like
var info = {
title: "your title"
}
then you can use like
<input ng-model="info.title" class="form-control" name="info.title" type="text" required/>
but you cant use new as a variable name. new is a reserved keyword

Related

How to use input field value attribute while using formControlName? [Angular]

What I want to achieve: I want pre-populated data in my form and I also want to use formControlName as I want the data too.
My html file -
<div class="container">
<p class="h4 my-5">Add New Result</p>
<div class="row">
<div class="col">
<form (ngSubmit)="editStudent()" [formGroup]="studentEditForm" name="myForm">
<div class="mb-3">
<label for="roll-no" class="form-label">Roll No.</label>
<input type="number" class="form-control" id="roll-no" name="rollno" formControlName="rollno" value="{{student.rollNo}}" placeholder="{{student.rollNo}}" autocomplete="off" required>
</div>
<div class="mb-3">
<label for="name" class="form-label">Name</label>
<input type="text" class="form-control" id="name" name="name" formControlName="name" value={{student.name}} required>
</div>
<div class="mb-3">
<label for="email" class="form-label">Email address</label>
<input type="email" class="form-control" id="email" name="email" formControlName="email" value={{student.email}} required>
</div>
<div class="mb-3">
<label for="score" class="form-label">Score</label>
<input type="number" class="form-control" id="score" name="score" formControlName="score" value={{student.score}} required>
</div>
<button type="submit" class="btn btn-primary" ng-click="submitForm(myForm.$valid)">Submit</button><button type="submit" class="btn btn-dark mx-4">Clear</button>
</form>
</div>
<div class="col"></div>
<div class="col"></div>
</div>
</div>
In Input Tag, I want to use value attribute so I can get a default value but I get Empty fields and I think it is because formControlName is controlling the data in my form. Is there a way to get pre-populated data using value attribute along with formControlName attribute?
Placeholder attribute works fine but I want a default value.
if you want a default value simply initialize the form with values, for example:
form = new FormGroup({
name: new FormControl('defaultNameValue'),
email: new FormControl('defaultEmailValue')
})
You should be doing it in you component instead of using value attribute. While defining the form example
studentEditForm= new FormGroup({
rollNo: new FormControl(this.student.rollNo)
})
or if student data is not available at the time of definition then use formcontrol.setValue after you initialize the student data something like
this.studentEditForm.controls.rollNo.setValue(this.student.rollNo)
Using the value and the CVA (Control Value Accessor: formControlName, formControl, and ngModel) to control the value of the input will override each other each time you change anyone of them.
Instead, it's better to rely only on one of them. If the CVA is used, then you can pass an initial value (default value) to the form-control while defining it:
studentEditForm = new FormGroup({
score: new FormControl(YOUR_INITIAL_VALUE),
});
For more info, check here how Angular passes the value from CVA to the value property when using both of them:
default_value_accessor.ts
Used value and CVA to control value
try this :
studentEditForm = new FormGroup({
score: new FormControl(VALUE),
});

input text isn't updating angular model in one case that is identical to another in the same form

I have a simple form (reduced from the actual form to demonstrate the problem):
<pre>Name: {{currentChild.name}}</pre>
<pre>Annual College Expense: {{currentChild.annualCollegeExpense}}</pre>
<form name="childForm" novalidate>
<div class="form-inline">
<div class="form-group">
<label>Name:</label>
<input type="text" name="name" class="form-control" ng-minlength="1" ng-model="currentChild.name" ng-required="true">
<div class="help-block"
ng-messages="childForm.name.$error"
ng-show="childForm.$submitted || childForm.name.$dirty || (childForm.name.$invalid && childForm.name.$touched)">
<p ng-message="required" ng-hide="childForm.name.$valid">Your name is required.</p>
<p ng-message="minlength" ng-hide="childForm.name.$valid">Your name is too short.</p>
</div>
</div>
<div class="form-group">
<label>Annual Expenses:</label>
<input type="text" name="annualCollegeExpense" class="form-control" ngModel="currentChild.annualCollegeExpense" />
</div>
</div>
</form>
When I fire up the form, I see the expected data in the pres at the top of the form. When I type into the name field, the name in the pre changes. When I type into annual expense field, the annual expense pre does NOT change.
Since these are IDENTICAL and appear to obey all the usual ng-model rules, i.e., use a . to reference the data in the model, I'm stumped.
Anybody got a suggestion?
you used ngModel instead of ng-model so you should use
ng-model="currentChild.annualCollegeExpense"
instead of
ngModel="currentChild.annualCollegeExpense"
use
<input type="text" name="annualCollegeExpense" class="form-control" ng-model="currentChild.annualCollegeExpense" />

How to create an HTML5 custom validation that check if the value inserted into 2 email inout field is the same?

I am pretty new in HTML 5 and I have the following doubt.
I have a form like this:
<form class="form-horizontal" action="/IDES/salvaRegistrazione" method="POST" name="formRegistrazione">
<div class="form-group">
<label class="control-label col-sm-2" for="inputNome">Nome</label>
<div class="col-sm-10">
<input id="inputNome" class="form-control" type="text" value="" required="required" placeholder="Nome" name="nome">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="inputEmail">E-mail</label>
<div class="col-sm-10">
<input id="inputEmail" class="form-control" type="email" value="" required="required" placeholder="E-mail" name="email">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="inputEmail2">E-mail</label>
<div class="col-sm-10">
<input id="inputEmail2" class="form-control" type="email" placeholder="Inserisci nuovamente E-mail" name="inputEmail2">
</div>
</div>
<input id="submitRegistrazione" class="btn btn-default pull-right" type="submit" value="Registrati" name="submitRegistrazione">
</form>
As you can see the input tag have setted the required="required" attribute and as you can see in this JSFiddle if you don't insert the value into the input tag it is automatically shown an HTML error message popup:
https://jsfiddle.net/fntwyn9j/
Now my problem is that into my form I have also 2 field having type="email".
My problem is that I want that if the second email value (the one inserted in the field having id="inputEmail2") is not equal to the first email value (the one inserted into the field having id="inputEmail") appear a custom message (in the same HTML5 style) that say to me that the 2 fields have not the same value and the form is not submitted.
Searching on the web I found this example that use event listener to add custom message: http://jsfiddle.net/B4hYG/9/
But is seems to me that don't work and I have no idea about how to implement the previous requirement.
How can I solve this issue and implement this kind of HTML5 custom validation?
Solved by myself:
$(document).ready(function() {
document.getElementById("inputEmail2").addEventListener("input", function (e) {
valoreInpitEmail = $('#inputEmail').val();
valoreInpitEmail2 = $('#inputEmail2').val();
//alert("value inputEmail: " + valoreInpitEmail + " value inputEmail2: " + valoreInpitEmail2);
//if (e.target.value != "") {
if(valoreInpitEmail != valoreInpitEmail2) {
alert("EMAIL DIVERSE");
//alert("BLABLABLA");
e.target.setCustomValidity("Le E-mail inserite non corrispondono, per favore inserirle nuovamente");
}
else {
// Let the browser decide whether this is a valid email address
// This actually prevents that the call of setCustomValidity()
// in the IF doesn't get removed thus the user cannot submit the form
//alert("ELSE");
e.target.setCustomValidity("");
}
});
});

equalTo validation with jQuery Validate

Below is my form which has password and confirm password field
<div class="form-group">
<label class="control-label">password</label>
<input type="text" class="form-control" name="password"
data-validate="minlength[8]"
data-message-required="email is required" placeholder="password">
</div>
<div class="form-group">
<label class="control-label">confirm password</label>
<input type="text" class="form-control" name="password_confirm"
data-validate="minlength[8],equalTo[password]"
data-message-required="email is required" placeholder="confirm password">
</div>
Below is my part of validation field.
if (params = rule.match(/(\w+)\[(.*?)\]/i)) {
if ($.inArray(params[1], ['minlength', 'equalTo']) != -1) {
opts['rules'][name][params[1]] = params[2];
message = $field.data('message-' + params[1]);
if (message) {
opts['messages'][name][params[1]] = message;
}
}
}
The minlength[8] seems to work perfectly, but when i try to match my password with confirm password its not working. I tried passing the name attribute in three ways, but none of them work.
equalTo[password]
equalTo["password"]
equalTo["#password"]
Also can anyone tell me what does this regular expression do /(\w+)\[(.*?)\]/i)
The parameter inside equalTo["#password"] is #password.
#password is a jQuery selector that matches an element with id="password". However, I don't see a id attribute on your password field. Try adding one...
<input type="text" class="form-control" id="password" name="password" ....
Quote OP:
"Also can anyone tell me what does this regular expression do /(\w+)\[(.*?)\]/i"
See: http://regexr.com/39d43

Validating a form with a dynamic name inside directive

<form name="{{ formname }}" novalidate>
<input type="text" ng-model="first_name" required>
<input type="text" ng-model="last_name" required>
<input type="text" ng-model="email" required>
<span class="error" ng-show="formname.$invalid">Fill in required fields.</span>
<button type="submit"></button>
</form>
I'm trying to validate the form using Angular's built in validation but because the formname is set dynamically by text passed in from the scope I'm not sure how to call it. This attempt above doesn't work.
You can do it with a little help from the controller. Define another variable (f in the example below), watch formname and update f accordingly:
.controller("...", function($scope) {
$scope.first_name = "";
$scope.formname = "fff";
$scope.f = null;
$scope.$watch("formname",function(newval,oldval,scope) {
scope.f = scope[newval];
});
});
See fiddle: http://jsfiddle.net/T7vuD/

Categories

Resources