when trying to open dialog in edit mode, validation message pop up with required message. but what i need to achieve is that when opening dialog box on edit mode as text box will contain value as soon as dialog box opens but then also validation message is there. how to remove that if already a value present in text box.
Example below for HTML code how I am using it.
<div class="form-group col-lg-6" show-errors>
<label for="firstName">First Name</label>
<input type="text" class="form-control" id="firstName" ng-model="firstName" name="firstName" placeholder="First Name" style="width: 74%;" required>
<p class="help-block" ng-if="EditUserUserform.firstName.$error.required">Required</p>
</div>
<div class="form-group col-lg-6" show-errors>
<label for="lastName">Last Name</label>
<input type="text" class="form-control" id="lastName" ng-model="lastName" name="lastName" placeholder="Last Name" style="width: 74%;" required>
<p class="help-block" ng-if="EditUserUserform.lastName.$error.required">Required</p>
</div>
app.directive('showErrors', function() {
return {
restrict: 'A',
require: '^form',
link: function (scope, el, attrs, formCtrl) {
// find the text box element, which has the 'name' attribute
var inputEl = el[0].querySelector("[name]");
// convert the native text box element to an angular element
var inputNgEl = angular.element(inputEl);
// get the name on the text box so we know the property to check
// on the form controller
var inputName = inputNgEl.attr('name');
// only apply the has-error class after the user leaves the text box
inputNgEl.bind('blur', function() {
el.toggleClass('has-error', formCtrl[inputName].$invalid);
});
}
}
});
Below is the image when i am opening form in normal mode.
And below image shows when i open in edit mode.
the value already present in it but as soon as dialog opens it show validation message.
I don't know angular at all and this is assuming you have access to the context of whether this is in edit mode or not, but it looks like you could do something here:
inputNgEl.bind('blur', function() {
//only check if not edit mode
if (!edit) {
el.toggleClass('has-error', formCtrl[inputName].$invalid);
}
});
unless angular has its own hooks to achieve the same thing, I'd say you could do it doing something like that.
Normally, if an input field hasn't been touched, the field's value didn't be filled by a user but by using controller , the $pristine will be true. So, you could fix this by firstly verifying the $pristine value:
// only apply the has-error class after the user leaves the text box
inputNgEl.bind('blur', function() {
// Only do this if and only if the field has been touched and the value is invalid
el.toggleClass('has-error', !formCtrl[inputName].$pristine && formCtrl[inputName].$invalid);
});
Alternatively, you could use $dirty value which will be false if the field hasn't been touched.
el.toggleClass('has-error', formCtrl[inputName].$dirty && formCtrl[inputName].$invalid);
Related
I am working on a reactive form in angular. Facing this problem where a field that is not required should have some validations when it is dirty or touched but as soon as the user is out of this textbox/field, the validation message should just go away. I have tried using ng-invalid but it is not working as the field when loaded for the first time is having ng-invalid class. The following is the code -
<div class="form-group">
<label>Street Name</label>
<input type="text" class="form-control" formControlName="streetName">
<span class="text-danger"
*ngIf="registerForm.get('streetName').touched || registerFormControl.get('streetName').dirty" class="Required">
<span *ngIf="registerForm.get('streetName').error?.pattern || registerForm.get('streetName').error?.minLength">
Pattern & Minlength error
</span>
<span class="text-danger"
*ngIf="registerForm.get('streetName').error?.monthError || registerForm.get('streetName').error?.otherError">
Month and Other Error
</span>
</span>
</div>
FormGroup Validation -
streetName:['',{
Validators: [
Validators.pattern(0-9),
Validators.minLength(9),
this.customValidations.streetValid
],
updateOn: 'blur'
}]
How do I get this validation dissappear?
You can use the focus and blur events to track if and when a user is in an input field or not.
<input (focus)="onFocus()" (blur)="onBlur()">
In this code example onFocus() is called when the user clicks/is-in the input box. onBlur() is called when the user clicks out of the input box.
We can use this to better distinguish if we should display the error message or not.
Let's say you have two inputs: Street Name and Street Address. We will create an onFocus() function that handles which item is focused and an onBlur() function that will clear the focused selection.
// Class variables
public selectedField = "";
function onFocus(identifier : string) {
selectedField = identifier; // set the field
}
function onBlur() {
selectedField = ""; // clear the field
}
Now, on our inputs:
<input (focus)="onFocus('streetName')" (blur)="onBlur()" type="text" class="form-control" formControlName="streetName">
<input (focus)="onFocus('streetAddress')" (blur)="onBlur()" type="text" class="form-control" formControlName="streetAddress">
Finally, we can handle if we should display the error message or not. All we need to do is add one more condition to the *ngIf of the error span.
<!--Example Street Name Error Span -->
<span class="text-danger" *ngIf="selectedField == 'streetName' && . . . ">
Invalid Street Name
</span
<!--Example Street Address Error Span -->
<span class="text-danger" *ngIf="selectedField == 'streetAddress' && . . . ">
Invalid Street Address
</span
If you'd like a better understanding on how focus works, you can find it here.
Could you please tell how to show red border in the input field on a button in angularJs . Currently, the red border is displayed when the application load. Actually, I added ng-required validation on my form .but I want this only work after button click here is my code
http://plnkr.co/edit/zL0cueTJN6xqxC4LzhOd?p=preview
<div class="form-group" ng-class="{'has-error': myform[key].$invalid}">
<input type="text" name="{{key}}" class="form-control" ng-model="value.value" ng-required="value.required">
</div>
Declare a variable $scope.isSubmitClicked=false; in scope and make it true in submit()
$scope.isSubmitClicked = false;
$scope.submit = function ($event) {
$scope.isSubmitClicked = true;
};
Then
<input type="text" name="{{key}}" class="form-control" ng-model="value.value" ng-required="value.required && isSubmitClicked">
helo guys I am writing ajava Script that have an input box to allow the user enter a value and I want to show him again what he enterd with in that page to ensure that he will see what he is enterd for example
<input id="userName" class="form-control col-md-7 col-xs-12" type="text" name="userName">
I have these input box and I want get this value and display it again in alabel bellow
<label id="user_label" class="control-label col-md-3 col-sm-3 col-xs-12"></label>
and I write the following JS
user_Name=getElementById('userName');
document.getElementById('user_label').innerHTML=user_Name;
and these displays the string userName not the string value init what can I do
Just grab the value from the HTML element instead...
var user_Name = document.getElementById('userName').value;
document.getElementById('user_label').innerHTML = user_Name;
What you need to do is call your code whenever the input field is changed.
<input id="userName" type="text" name="userName" onKeyUp="update()">
And in JS:
function update() {
var user_Name=document.getElementById('userName').value;
document.getElementById('user_label').innerHTML=user_Name;
}
Also you need to refer to the .value of the input element to get its value.
Here is a Pen:
http://codepen.io/calvinclaus/pen/EKBvBz?editors=1011
Try:
var user_Name=getElementById('userName');
document.getElementById('user_label').innerHTML=user_Name.value;
I am using jQuery Mobile and am attempting to use HTML5 form field validation to perform inline form field validation. I am doing this because I really like the way that the browser reports issues in the bubble and I don't think it is very user friendly to wait until someone has completed filling out a form and then tell them what is wrong. Here is my HTML:
<form id="frmMain" action="#">
<input type="checkbox" data-enhance="false" value="1" id="cbxFB" />
<label for="cbxFB">
<span class="formsubtext">Check this box to use Facebook information to help fill out this registration. Once registered you will be able to use the Facebook login button.</span>
</label>
<label for="tbEmail">*Email</label><input type="email" id="tbEmail" required autofocus placeholder="example#address.com" />
<label for="tbPassword">*Password</label><input type="password" id="tbPassword" required />
<div class="formsubtext" style="margin-top:1px; padding-top:0px; margin-bottom:10px">Minimum of 6 characters, one capital character, and one lower case character.</div>
<label for="tbPasswordConfirm">*Password Confirm</label><input type="password" id="tbPasswordConfirm" required />
<label for="tbPin">*Account Pin</label><input type="password" pattern="[0-9]{4}" id="tbPin" required placeholder="####" />
<div class="formsubtext" style="margin-top:1px; padding-top:0px; margin-bottom:10px">A four digit number that you will remember. This value will be needed to perform sensitive tasks within the application.</div>
<label for="tbFName">*First Name</label><input type="text" id="tbFName" required />
<label for="tbLName">*Last Name</label><input type="text" id="tbLName" required />
<label for="tbPhone">Phone Number</label><input type="tel" id="tbPhone" pattern="\d{3}[\-]\d{3}[\-]\d{4}" placeholder="###-###-####" style="margin-bottom:1px; padding-bottom:0px;" />
<div class="formsubtext" style="margin-top:1px; padding-top:0px; margin-bottom:20px;">Used at your option when you schedule an appointment with a service provider</div>
<div style="display:none;"><label for="tbfbID">Facebook ID</label><input type="text" id="tbfbID" /></div>
<input type="submit" id="btnMainNext" data-icon="arrow-r" data-iconpos="right" value="Next" data-theme="c" class="ui-btn-c ui-btn ui-corner-all" />
</form>
For the confirm password form field I have the following event defined:
$("#tbPasswordConfirm").on("change", function (event) {
var password = $("#tbPassword").val();
var passwordconfirm = $("#tbPasswordConfirm").val();
if (password != passwordconfirm) {
$("#tbPasswordConfirm")[0].setCustomValidity("The value entered does not match the previous password entered.");
$("#btnMainNext").click();
}
else {
$("#tbPasswordConfirm")[0].setCustomValidity("");
}
$(this).focus().select();
})
My problem is that when the user enters something into the field and moves to the next field the HTML form validation shows the error message for the next field (which is required). I want it to show the message for the field they just left. How do I stop the focus from moving to the next field so that the bubble message that shows up is from the field they just entered the data into? As you can see I have tried setting the focus but that does not work. Any help would be greatly appreciated.
You can stop focus from moving to the next field but you can't trigger native validation UI or error message unless you click submit button.
To stop focus from moving next field, after you set the custom validity on the field, you can use:
$('#tbPasswordConfirm').blur(function(event) {
event.target.checkValidity();
}).bind('invalid', function(event) {
setTimeout(function() { $(event.target).focus();}, 50);
});
The blur() function will check the validity on blur and if it would be invalid, the corresponding function in bind() would set the focus back to that element.
Solved it
Fiddle
$(function() {
$("#tbPasswordConfirm").on("input", function(event) {
var thisField = $("#tbPasswordConfirm")[0],
theForm = $("#frmMain")[0],
password = $("#tbPassword").val(),
passwordconfirm = $(this).val(),
custom = password === passwordconfirm ? "" : "The value entered does not match the previous password entered.";
thisField.setCustomValidity(custom);
if (!theForm.checkValidity()) theForm.reportValidity();
});
});
You can use html tabindex attr to manipulate which element will get the focus when you click tab character. See docs to how to use it.
For example, if you make your password confirm input as tabindex="5", you can add tabindex="6" to the <label for="tbPin"> element to prevent next input from focusing right after.
Having such form
<div ng-controller="FormController as f_ctrl">
<form ng-submit="f_ctrl.submit()" name="myForm">
<input type="text" ng-model="f_ctrl.user.username"
required
ng-minlength="4"/>
<input type="text" ng-model="f_ctrl.user.password"/>
<input type="submit" value="Submit" ng-disabled="myForm.$invalid">
</form>
</div>
and such controller
.controller('FormController', [function() {
var self = this;
self.submit = function() {
console.log('User submitted form with ' + self.user.username)
}
}]);
I have a problem: when page first loads it immediately shows red border on username field, even before I start typing anything.
I need to highlight invalid fields only after first submission. Can this be done using form.$invalid ?
You have to use $pristine for that. It is true when form controller is not changed. so when you change textbox data its comes false.
Small example for you.
<div class="form-group" ng-class="{ 'has-error' : userForm.password.$invalid && !userForm.password.$pristine }">
<input id="passAnime" type="password" name="password" ng-model="user.password" class="form-control input-md" placeholder="Password" tabindex="5" ng-maxlength="25" ng-minlength="6" required>
<span ng-show="userForm.password.$dirty && userForm.password.$invalid">
<p ng-show="userForm.password.$error.required" class="error-messages">
Your password is required.
</p>
<p ng-show="userForm.password.$error.minlength" class="error-messages">
Your password is too short. Minimum 6 chars.
</p>
<p ng-show="userForm.password.$error.maxlength" class="error-messages">
Your password is too long. Maximum 25 chars.
</p>
</span>
</div>
Angular has helpers that tell you if the form (or form field) is $dirty (user has typed something) or if the form is $touched (the blur event has been triggered on the input). See this demo.
I need to highlight invalid fields only after first submission.
Unfortunately, Angular doesn't support that. But you could implement it yourself rather easily:
Controller
function FormController() {
var vm = this;
vm.submitAttempted = false;
vm.submit = function(isValid) {
if (isValid) {
// do stuff
}
else {
vm.submitAttempted = true;
}
};
}
HTML
<div ng-app='app'>
<div ng-controller='FormController as vm'>
<form name='fooForm' ng-submit='vm.submit(fooForm.$valid)' novalidate>
<label>Username</label>
<input
name='username'
type='text'
ng-model='vm.user.username'
required
ng-minlength='4'
ng-class="{'invalid': vm.submitAttempted && fooForm.username.$invalid}">
<br /><br />
<button type='submit'>Submit</button>
</form>
</div>
</div>
CSS
.invalid {
border-color: red;
}
Demo
I have a problem: when page first loads it immediately shows red border on username field, even before I start typing anything.
That's probably because you have the following CSS class:
.ng-invalid {
border-color: red;
}
Angular will always apply the ng-invalid class to fields that are invalid, and there's nothing you could do about that. So if you don't always want invalid fields to have a red border, you can't use that class and you should do it in a way similar to what I proposed above.
Also, check out ngMessages.
You can disable the default styling on the input field that is adding the red border by default, by adding the following CSS:
input:required {
-moz-box-shadow: none;
box-shadow: none;
}
Then if you want to highlight the field when the form is submitted, you will need to ensure that the form and form fields have relevant name attributes. Doing this will allow you to check if the field is valid or not and apply a class to your text field when it is invalid:
<input type="text" name="username" ng-class="{ 'invalid-field' : f_ctrl.myForm.username.$invalid && !f_ctrl.myForm.username.$pristine }" required />
f_ctrl.myForm and f_ctrl.myform.username will have additional properties that you can use/check to determine if the form or fields are invalid or not, or if they have been modified at any point (e.g. f_ctrl.myform.username.$dirty). You should be able to view these properties on your page by adding the follow HTML:
<div>
<pre>{{f_ctrl.myForm | json}}</pre>
</div>
Or, you could output self.myForm to the console from your controller to view it's properties
console.log(self.myForm);