Angular is automatically adding 'ng-invalid' class on 'required' fields - javascript

I am building an angular app for which I have some forms set up.
I have some fields that are required to be filled before submission. Therefore I have added 'required' on them:
<input type="text" class="form-control" placeholder="Test" ng-model="data.test" required>
However when I launch my app, the fields are displayed as 'invalid' and the classes 'ng-invalid' and 'ng-invalid-required' even before the submit button has been click or before the user has typed anything in the fields.
How can I make sure that thoses 2 classes are not added immediately but either once the user has submitted the form or when he has typed something wrong in the corresponding field?

Since the inputs are empty and therefore invalid when instantiated, Angular correctly adds the ng-invalid class.
A CSS rule you might try:
input.ng-dirty.ng-invalid {
color: red
}
Which basically states when the field has had something entered into it at some point since the page loaded and wasn't reset to pristine by $scope.formName.setPristine(true) and something wasn't yet entered and it's invalid then the text turns red.
Other useful classes for Angular forms (see input for future reference )
ng-valid-maxlength - when ng-maxlength passes
ng-valid-minlength - when ng-minlength passes
ng-valid-pattern - when ng-pattern passes
ng-dirty - when the form has had something entered since the form loaded
ng-pristine - when the form input has had nothing inserted since loaded (or it was reset via setPristine(true) on the form)
ng-invalid - when any validation fails (required, minlength, custom ones, etc)
Likewise there is also ng-invalid-<name> for all these patterns and any custom ones created.

Thanks to this post, I use this style to remove the red border that appears automatically with bootstrap when a required field is displayed, but user didn't have a chance to input anything already:
input.ng-pristine.ng-invalid {
-webkit-box-shadow: none;
-ms-box-shadow: none;
box-shadow:none;
}

Since the fields are empty they are not valid, so the ng-invalid and ng-invalid-required classes are added properly.
You can use the class ng-pristine to check out whether the fields have already been used or not.

Try to add the class for validation dynamically, when the form has been submitted or the field is invalid. Use the form name and add the 'name' attribute to the input. Example with Bootstrap:
<div class="form-group" ng-class="{'has-error': myForm.$submitted && (myForm.username.$invalid && !myForm.username.$pristine)}">
<label class="col-sm-2 control-label" for="username">Username*</label>
<div class="col-sm-10 col-md-9">
<input ng-model="data.username" id="username" name="username" type="text" class="form-control input-md" required>
</div>
</div>
It is also important, that your form has the ng-submit="" attribute:
<form name="myForm" ng-submit="checkSubmit()" novalidate>
<!-- input fields here -->
....
<button type="submit">Submit</button>
</form>
You can also add an optional function for validation to the form:
//within your controller (some extras...)
$scope.checkSubmit = function () {
if ($scope.myForm.$valid) {
alert('All good...'); //next step!
}
else {
alert('Not all fields valid! Do something...');
}
}
Now, when you load your app the class 'has-error' will only be added when the form is submitted or the field has been touched.
Instead of:
!myForm.username.$pristine
You could also use:
myForm.username.$dirty

the accepted answer is correct.. for mobile you can also use this (ng-touched rather ng-dirty)
input.ng-invalid.ng-touched{
border-bottom: 1px solid #e74c3c !important;
}

Related

change background color when value of an input field has changed?

I have an angular reactive form, I would like to change the background color of all the input fields when the value is changed. Some of the input fields are pre populated and not required fields. I tried the following solution I found out, but it requires my input fields to be required:
<div class="form-group">
<input type="text" class="form-control" required>
</div>
.form-control:valid {
background-color: #96d3ec!important;
}
Wondering if form-control has anything like:
.form-control:changed {
background-color: #96d3ec!important;
}
The solution you found, doesn't require the your input fields to be required. ( The second code snippet of the solution ).
Only the first code snippet of the solution needs the required field, to ensure validation.
Nope!you can check all the rest pseudo-classes here https://developer.mozilla.org/en-US/docs/Web/CSS/:valid
and there's no :change pseudo class.
Please use change event to implement this function.

Bootstrap validation conflicts

I am using Vue.js and Bootstrap to design a website. I have a form that I am trying to run my custom validation on. It works fine until the user clicks submit which adds the was-validated class to the form per the bootstrap documentation.
At this point any required input field that has any input whether it meets my custom validation or not is marked as valid and gets a green border and check mark. My custom validation is still being run and displaying b-form-invalid-feedback correctly. However, it seems that was-validated is marking fields with the required prop as valid while not taking my custom validation into account this is leading to conflicting validation as a field has a green check mark (because it satisfies the required property) but still an error message because it is not yet valid per my custom validation.
I have tried removing the :valid style this isn't the effect I want as I do want it to display those styles when it is valid per my validation. Hope this makes sense if not I will provide pictures. I also have a second issue I have a date picker that is not displaying b-form-invalid-feedback at all even when was-validated is added.
My Code
<b-form #submit.prevent="addReview" name="review-form" novalidate>
<div class="name">
<label class="sr-only" for="form-input-name">Name</label>
<b-input id="form-input-name" class="form-inputs mb-2 mr-sm-2 mb-sm-0" v-model="name" placeholder="Name" required :state="isStateValid(this.name)"></b-input>
<b-form-invalid-feedback id="form-input-name">
You must enter a name
</b-form-invalid-feedback>
</div>
<div class="date">
<label class="sr-only" for="example-datepicker">Choose a date</label>
<b-form-datepicker id="datepicker" v-model="dateVisited" class="mb-2" required placeholder="Date Visited" :state="isStateValid(this.dateVisited)"></b-form-datepicker>
<b-form-invalid-feedback id="datepicker">
You must enter a valid date
</b-form-invalid-feedback>
</div>
<div class="service">
<label class="sr-only" for="form-input-service">Service Provided</label>
<b-input id="form-input-service" class="form-inputs mb-2" placeholder="Service Provided" v-model="service" required :state="isStateValid(this.service)"></b-input>
<b-form-invalid-feedback id="form-input-service">
You must enter the service provided
</b-form-invalid-feedback>
</div>
<div class="email">
<label class="sr-only" for="inline-form-input-username">Email</label>
<b-input id="inline-form-input-username" class="form-control mb-2 mr-sm-2 mb-sm-0" placeholder="Email" v-model="email" required :state="emailStateValidation"></b-input>
<b-form-invalid-feedback id="inline-form-input-username">
You must enter the part of your email that comes before the '#' symbol
</b-form-invalid-feedback>
</div>
<div class="domain">
<label class="sr-only" for="inline-form-input-domain">Domain</label>
<b-input-group prepend="#" class="mb-2 mr-sm-2 mb-sm-0">
<b-input id="inline-form-input-domain" placeholder="Domain ex: gmail.com" v-model="domain" required :state="domainStateValidation"></b-input>
<b-form-invalid-feedback id="inline-form-input-domain">
You must enter the part of your email that comes after the '#' symbol
</b-form-invalid-feedback>
</b-input-group>
</div>
<div class="description">
<label class="sr-only" for="textarea-rows">Describe Your Experience</label>
<b-form-textarea class="mb-3 mr-sm-2 mb-sm-0" id="textarea-rows" placeholder="Describe Your Experience" rows="4" required v-model="description" :state="isStateValid(this.description)"></b-form-textarea>
<b-form-invalid-feedback id="textarea-rows">
You must enter a description of your experience
</b-form-invalid-feedback>
</div>
<b-button type="submit">Save</b-button>
</b-form>
computed: {
emailStateValidation() {
if (this.email) {
return this.emailIsValid() ? true : false;
}
return null;
},
domainStateValidation() {
if (this.domain) {
return this.domainIsValid() ? true : false;
}
return null;
},
},
methods: {
emailIsValid() {
let regEx = /^(?!.*#)((^[^\.])[a-z0-9\.!#$%&'*+\-\/=?^_`{|}~"]*)*([^\.]$)/;
return regEx.test(this.email);
},
domainIsValid() {
let regEx = /((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return regEx.test(this.domain);
},
isStateValid(variable) {
if (variable) {
return variable.length > 0 ? true : false;
}
return null;
},
addReview() {
let mainForm = document.getElementsByName("review-form")[0];
mainForm.classList.add("was-validated");
...
Questions
Resolve the conflict between required and my custom validation
causing input fields being prematurely marked as valid
Display b-form-invalid-feedback on datepicker on form submit if
date is not selected
In a nutshell, remove novalidate from <form> in your Vue template. When you set novalidate, the inputs will remain in their :valid state throughout their lifecycle until you explicitly call setCustomValidity. Working Sandbox
Since, Bootstrap styles also apply to :valid or :invalid states so, even if your custom validators determine inputs to be invalid, both valid and invalid styles will get applied i.e. :valid and .is-invalid but, I guess it's just happens so, that :valid styles take precedence the way Bootstrap stylesheet is currently written.
U̶s̶e̶ ̶̶n̶o̶v̶a̶l̶i̶d̶a̶t̶e̶̶ ̶w̶h̶e̶n̶ ̶y̶o̶u̶'̶r̶e̶ ̶i̶m̶p̶l̶e̶m̶e̶n̶t̶i̶n̶g̶ ̶a̶ ̶c̶o̶m̶p̶l̶e̶t̶e̶ ̶v̶a̶l̶i̶d̶a̶t̶i̶o̶n̶ ̶s̶o̶l̶u̶t̶i̶o̶n̶ ̶y̶o̶u̶r̶s̶e̶l̶f̶ ̶i̶n̶c̶l̶u̶d̶i̶n̶g̶ ̶̶r̶e̶q̶u̶i̶r̶e̶d̶̶ ̶v̶a̶l̶i̶d̶a̶t̶o̶r̶.̶
With Bootstrap, since it also applies styles to :valid or :invalid states of input, you're better off NOT using novalidate.
Ofcourse, this will enable browser popups asking for filling certain fields which might be unwanted.
Suggestion: Use validated prop on your form and bind it to your form's state and set it to true in addReview(), it will automatically add was-validated class and you don't need to manipulate the DOM directly.
EDIT: Since removing novalidate enables browser validation, submit event no longer fired on the form and hence, was-validated class is never added to the form. This presented an issue in my original answer because messages and icon were not shown without was-validated. I have modified the sandbox to suggest a fix for that and that is to bind click event to submit button for validation logic and using submit event for stuff that should happen after successful validation.
EDIT for Datepicker: The reason why datepicker never invalidated was because of an issue in isStateValid() method specifically the part:
if(variable) { // "" evaluates to false
// ...
}
Since "" evaluates to false, it will always return null. The fix for that is in combination with the suggestion above of maintaining validated state for the form. Now, instead of checking if(variable), we check if(this.validated) and if it is true, we simply check the length and return either true or false.
Fundamentally was-validated is not bootstrap-vue native, it's browser native, which also has no understanding of :state. If you want to use was-validated you can't use custom validations. If you want to use custom validations. See the suggestion For 2. Which is basically, use another variable to control whether validation should be applied.
From the documentation on bootstrap-vue
When set, adds the aria-required="true" attribute on the component. Required validation needs to be handled by your application
You need to explicitly check that the validation should show, it isn't clear from the documentation what required actually does, but it doesn't affect validation. Which explains why that part isn't working. Personally I set a global this.showValidations = true on submit, so that the validations actually run at the right time and not before (and after when expected). In your case, you can check for the was-validated class that you are adding explicitly. It isn't great, but it seems it must be done here.

Getting the field of form angular

I have a form with some fields.
I'm validating the fields with css classes:(if the field is invalid and the user touched it, then input's border-color = red.)
select.ng-invalid.ng-touched,
input.ng-invalid.ng-touched,textarea.ng-invalid.ng-touched {
border-color: red;
}
If the user submits the form without filling one or more field, there would be a danger alert.
HTML:
<div ng-show="formInvalid>
error!
</div>
JS:
if ($scope.pniyaForm.$valid) {
$scope.formInvalid = false;
.....
} else {
$scope.formInvalid = true;
}
But, If the user submits the form and has not touched any of the field, the css classes don't influence.(because user didn't touch...)
I want to add the class in the code.
Does anyone have an idea for an elegant way to do this without writing it on each field separately?
A possible solution:
when you are executing your form function, add the following line into it.
$scope.$apply(function () {});
this line will cause the ng $scope.$watch() run and apply changes if they exist.
may work, may not work, read the following link for deeper understanding of the issue.
http://jimhoskins.com/2012/12/17/angularjs-and-apply.html
Using ng-class validation in angularjs
<div class="form-group">
<label>Name</label>
<input type="text" required ng-model="name" name="name" ng-class="{'has-error': myForm.name.$invalid}" />
</div>
<div class="form-group">
<label>Age</label>
<input type="text" required ng-model="age" name="age" ng-class="{'has-error': myForm.age.$invalid}" />
</div>
If the user submits the form and has not touched any of the field, the css classes don't influence
You need to provide an initial defined value to an ngModel and at least provide the required attribute to an input.
Use ngClass to conditionally apply css classes in case some form parts are invalid
<form name="myform">
<div class="form-group" ng-class="{'has-error': myform.myinput.$invalid}">
<input name="myinput" ng-model="myName" class="...." required>
</div>
....
</form>
....
// in controller
$scope.myName = "cats"; // form is valid
$scope.myName = ""; // form is invalid, and the css class 'has-error' will be applied
Then use ngDisables in your submit button to prevent submission in case the form is invalid
<button type="submit" ng-disabled="myform.$invalid">submit</button>

Required attribute to be shown visually

I have a form where some fields are required, and some others aren't.
Now:
Does Polymer provide any "out-of-the-box" way to mark an element as "required"?
If not, what's the best way, in CSS, to show that a field is required?
At the moment, once the form is submitted the required fields will be shown as such. However, this happens after the form is submitted (or attempted).
I would like the user to know that while the first name is required, the middle name isn't.
Am I missing something very obvious?
One way would be to use attribute prefix or suffix
<paper-input label="First Name">
<div prefix>*</div>
<div suffix>*</div>
</paper-input>
Another way would be to create a new input element
<span hidden={{!required}} class="required"> * </span>
<paper-input-container no-label-float="[[noLabelFloat]]"
always-float-label="[[_computeAlwaysFloatLabel(alwaysFloatLabel,placeholder)]]"
auto-validate$="[[autoValidate]]"
disabled$="[[disabled]]"
invalid="[[invalid]]">
But this does not make sense only for required field as you will have to emulate/copy the complete paper-input code
Here is basic example how I'm validating the inputs: Plunk
On each input change call the validation method,
if it passes - submit the form.
<paper-input
id="step"
type="number"
min="1"
max="10"
value="{{value}}"
editable
required
auto-validate="true"
invalid="{{invalid}}"
preventInvalidInput
error-message="value: {{value}} - means invalid is {{invalid}}"
on-change="stepChange">
</paper-input>
stepChange: function(e, detail) {
//validation code
//Fields must be revalidated on each change
var step = this.$.step;
var val_step = step.validate();
// if alll the inputs are valid then submit the form
if ( false == val_step )
{
console.log("not invalid");
}
else
{
console.log("invalid");
}
},

Check which field is not valid in form with Angular

I need to check which fields aren't valid after 5 seconds when form is rendered. I have a button and I set this ng-disabled="!step1Form.$valid" but I need to add some kind of CSS class maybe red to fields which are not valid, can any give me some help?
This is the field where I want to set the invalid pattern:
<div ng-form="logoForm" style="position:absolute;top:0px;left:0px;" class="info-picture main ng-pristine ng-invalid ng-invalid-required">
<div add-pic="" class="small-button">Agregar logo</div>
<input type="file" required="required" ng-model="logo.company" id="company_logo" style="display:none;" ng-file-select="" class="ng-pristine ng-invalid ng-invalid-required">
</div>
If you want to add css Class to any component you can use the "ng-class" directive.
You can see this in documentation at http://docs.angularjs.org/api/ng/directive/ngClass
Another question like yours is this: How to set Twitter Bootstrap class=error based on AngularJS input class=ng-invalid?

Categories