I have an Angular form inside a ng2 popup:
<popup>
Sign up for our Newsletter! <form #f="ngForm" (ngSubmit)="onSubmit()" novalidate>
</button> <input type="email"/>
<button>Submit</button>
</form>
</popup>
<button class="submit" (click)="ClickButton()">Sign up for our Newsletter </button>
here is the onClick event function:
constructor(private popup:Popup) { }
testAlert() { ClickButton(){
alert("Newsletter event works"); this.popup.options = {
widthProsentage: 15,
showButtons: false,
header: "Sign up for our Newsletter!",
}
this.popup.show(this.popup.options);
}
It works fine but I am able to submit her even if the input is blank, how can I make so that it does not submit if it is clicked empty
I tried using RegEx but it did not work
Consider adding validation.
Something like this:
<div class="form-group row">
<label class="col-md-2 col-form-label"
for="userNameId">User Name</label>
<div class="col-md-8">
<input class="form-control"
id="userNameId"
type="text"
placeholder="User Name (required)"
required
(ngModel)="userName"
name="userName"
#userNameVar="ngModel"
[ngClass]="{'is-invalid': (userNameVar.touched || userNameVar.dirty) && !userNameVar.valid }" />
<span class="invalid-feedback">
<span *ngIf="userNameVar.errors?.required">
User name is required.
</span>
</span>
</div>
</div>
You can then disable the submit button if the fields are not valid:
<button class="btn btn-primary"
type="submit"
style="width:80px;margin-right:10px"
[disabled]="!loginForm.valid">
Log In
</button>
(ngSubmit) is built-in event emitter inside of Angular ngForm and is directly related to button element which is kind of a trigger for form submission.
Therefore, as lealceldeiro said, you only need onSubmit function and button intended for submission inside of your form tag.
Please provide live demo so we can see the whole file (.ts particularly).
Setting the validation properly depends on what kind of forms you're going to use (template or ReactiveForms).
See more about proper ngForm usage in official documentation.
Related
i'm using bootstrap's form validation to validate a form. i wan to add an extra field called discount code. this field should accept only specified codes. when the field is empty it should light green, when the code is right it should light green and when the code is wrong it should light red. how can i do that using the bootstrap form validation?
thats how my form almost looks like
<form class="needs-validation" novalidate>
<div class="form-group">
<div class="col-md-12">
<strong>Enter your name </strong>
<input type="text" name="name" id="name" class="form-control" value="" required minlength="3" />
<div class="invalid-feedback">
Name should be at least 3 characters
</div>
</div>
</div>
<div class="col-12">
<button class="btn btn-primary" type="submit">Submit form</button>
</div>
</form>
<script>
(function () {
'use strict'
// Fetch all the forms we want to apply custom Bootstrap validation styles to
var forms = document.querySelectorAll('.needs-validation')
// Loop over them and prevent submission
Array.prototype.slice.call(forms)
.forEach(function (form) {
form.addEventListener('submit', function (event) {
if (!form.checkValidity()) {
event.preventDefault()
event.stopPropagation()
}
form.classList.add('was-validated')
}, false)
})
})()
</script>
I am having a problem with using 'enter button' on the keyboard with an angular js login form. I know this question is asked before but I believe that my problem is a bit different because I tried almost everything written on the stackoverflow questions.
So, I just want to be able to hit enter and submit the form with only using the enter key on keyboard.
Here is login html:
<!-- BEGIN LOGIN FORM -->
<form ng-submit="loginCtrl.login()" class="login-form">
<h3 class="form-title">Sign In</h3>
<div class="alert alert-danger display-hide">
<button class="close" data-close="alert"></button>
<span>
Enter any username and password. </span>
</div>
<div class="form-group">
<!--ie8, ie9 does not support html5 placeholder, so we just show field title for that-->
<label class="control-label visible-ie8 visible-ie9">Username</label>
<input class="form-control form-control-solid placeholder-no-fix" type="text" autocomplete="off" placeholder="Company/username"
ng-model="loginCtrl.username" name="username"/>
</div>
<div class="form-group">
<label class="control-label visible-ie8 visible-ie9">Password</label>
<input class="form-control form-control-solid placeholder-no-fix" type="password" autocomplete="off" placeholder="Password"
ng-model="loginCtrl.password" name="password"/>
</div>
<div class="form-actions">
<input type="submit" class="btn btn-success uppercase" value="Login">
</div>
</form>
<!-- END LOGIN FORM -->
and here is my login:
self.login = function() {
var result = self.username.split("/");
var account = result[0];
var userId = result[1];
UserService.login(userId, self.password,account).then(function(user) {
self.userAccount = user;
$state.go('home');
}, function(err) {
alert("Authentication failure: Please check your credentials. ")
});
I get user name as "companyName/Username" so it is like:
amazon/bigboby
I'm pretty sure your problem is caused by this <button> tag:
<button class="close" data-close="alert"></button>
The answer is found in the documentation:
You can use one of the following two ways to specify what javascript method should be called when a form is submitted:
ngSubmit directive on the form element
ngClick directive on the first button or input field of type submit (input[type=submit])
Note the comment about how it looks for an ng-click handler on the first button. When you are pressing ENTER to submit the form, Angular looks at the form and sees that button. It would execute the ng-click handler on that button (if it had one).
If you include the type attribute on the button, you can prevent that and let it find the actual submit button:
<button type="button" class="close" data-close="alert"></button>
I have an Angular page with a form for adding people, and a button (outside this form) to submit the list of people.
When the user focuses on a text input in the form, and then clicks to submit the list, the validation error from the text input appears but the submit event never occurs.
An example of this issue here: http://plnkr.co/edit/6Z0UUs
<div ng-controller="MyCtrl as vm">
<form name="form1" novalidate="">
<input type="text" name="field1" ng-model="vm.name" required>
<div ng-messages="form1.field1.$error" ng-if="form1.field1.$touched">
<label ng-message="required">Name is required</label>
</div>
<!--
This form adds a person to a list. I've not included this code to keep the example simple
<input type="submit" value="Add person">
-->
</form>
<button ng-click="vm.submit()">Submit list</button>
</div>
-
angular.module('myApp',[])
.controller('MyCtrl', function() {
var vm = this;
vm.name = '';
vm.submit = function () {
alert('submitted');
};
});
To replicate:
Click on the text input but leave blank
Click submit
Current behavior: "Name is required" appears thanks to the validation. Clicking 'Submit' again displays the 'submitted' alert.
Expected behavior: "Name is required" appears thanks to the validation and the 'submitted' alert appears.
Desired behavior: The 'submitted' alert appears and I add some code to vm.submit() to hide the 'Name is required' validation message as it's not important when the list is submitted.
I've observed that removing the ng-messages block fixes the issue, but I do need to show a validation message. Using a more basic directive (ng-show) to show the validation message instead does not help.
Any insights into what I'm doing wrong, or workarounds to achieve my desired behavior, would be great!
[Modified Answer] :
Here is a working plunker : http://plnkr.co/edit/JCyRi8xp4L3FtafABblS?p=preview
vm.preventDefaultIfSubmitted = function($event){
if($event.relatedTarget.id == "submit"){
$event.stopImmediatePropagation();
}
};
The idea is to get the $event when the blur occurs and then to look at the id of the relatedTarget (which is your button in this case) and if it is then you cancel the $event, otherwise you keep it.
That way if you click anywhere your validation message appears and if you click on submit it doesnt
May this help for form validation
<form role="form" name="projectBriefFrm">
<div class="form-group">
<label for="project_title">Project Title
<sup>*</sup>
</label>
<input ng-model="project.title" ng-required="true" type="text" class="form-control" name="title" placeholder="Untitled Project"
/>
<div class="row">
<span class="errorMessage" ng-show="!isProjectModelValid && projectBriefFrm.title.$invalid">Please provide title</span>
</div>
<div class="container" id="editor-title">
<label for="project_brief">Project Brief
<sup>*</sup>
</label>
<div class="row" id="editor">
<div class="col-lg-12 nopadding">
<textarea ng-model="project.brief" name="brief" cult-editor ng-required="true"></textarea>
</div>
</div>
</div>
<div class="row">
<span class="errorMessage" ng-show="!isProjectModelValid && projectBriefFrm.brief.$invalid">Please provide project brief</span>
</div>
</div>
</form>
I have the following form:
<form class="form-horizontal" {{action "formSubmit"}}>
<div class="form-group">
<label>User:</label>
{{input type="text" value=user action="findUser"}}
</div>
<div class="form-group">
<label>Notes:</label>
{{input type="text" value=notes}}
</div>
<button type="submit" class="btn btn-primary">Save</button>
</form>
As you notice, I have two actions for this form:
When I type on the user input field and press enter, it fires the findUser action
When the form submits, the formSubmit action is called.
Now, here's the problem.
When I type something on the user text field and press enter, it fires the findUser action but also fires the formSubmit. As I know, this is how a form normally behaves. When you press enter on a text field, it submits the form.
Is there a workaround on this behavior? That when I press enter on a the user text field, I want the findUser action to be fired but not submit the form.
Please help.
One workaround is removing form itself. You can have action on button. You may have to sacrifice some form related features but still works very well. Here is the jsbin.
http://emberjs.jsbin.com/nifim/2/edit
There might be some other better way as well.
<div class="form-group">
<label>User:</label>
{{input type="text" value=user action="findUser" bubbles=false}}
</div>
<div class="form-group">
<label>Notes:</label>
{{input type="text" value=notes}}
</div>
<button type="submit" class="btn btn-primary" {{action "formSubmit"}}>Save</button>
and javascript
App.IndexController = Ember.Controller.extend({
actions: {
findUser: function(){
console.log('Find User');
},
formSubmit: function(){
console.log('Form Submit');
}
}
});
Another workaround that allows using the form:
http://emberjs.jsbin.com/povud/1/
Just add 'onkeypress="return event.keyCode != 13;"' to the form element and place the {{action}} on the button itself:
<form class="form-horizontal" onkeypress="return event.keyCode != 13;">
<div class="form-group">
<label>User:</label>
{{input type="text" value=user action="findUser"}}
</div>
<div class="form-group">
<label>Notes:</label>
{{input type="text" value=notes}}
</div>
<button class="btn btn-primary" {{action "formSubmit"}}>Save</button>
</form>
The code appears to be hooked up (like this)
jQuery("#contactForm").validationEngine();
because it will validate and raise an error bubble if:
you tab out of required field without any input
you type at least one character into a field that requires more and then click the submit button
But it will not validate and raise an error bubble if you do nothing at all except click the submit button. In that case, it just submits. Once you click in the field or enter anything at all, it seems to work.
What can I be looking for that I've mis-configured?
The HTML:
<form class = "contactform" id = "contactForm">
<fieldset>
<div class="contactform-name contactform-field">
<label class="contactform-label" for="contactform-name">Name:
<br>
</label>
<input class="validate[required,minSize[8]] contactform-input" type="text" id="contactform-name" name="name" />
</div>
<div class="contactform-email contactform-field">
<label class="contactform-label" for="contactform-email">Email Address:<br></label>
<input value class="validate[required,custom[email]] contactform-input" type="email" id="contactform-email" name="contactform-email" />
</div>
<div class="contactform-text contactform-field">
<label class="contactform-label" for="contactform-text">Message:
<br>
</label>
<textarea class="validate[required,minSize[12]]contactform-input" name="text" id="contactform-text" > </textarea>
</div>
<input class="contactform-button" type="submit" name="submit" value="Send" />
</fieldset>
</form>
The JavaScript (it's running in Meteor):
Template.Contact.rendered = function () {
jQuery("#contactForm").validationEngine();
}
I've never used this engine, but from the docs I found that 'attach' will attach the validator to form.submit. Can it be as simple as that?
https://github.com/posabsolute/jQuery-Validation-Engine#attach
EDIT:
You can also do stuff to the submit-event (if the tip above won't help).
Something like this (not tested, but should put you in the correct path):
Template.templateName.events({
'submit': function(event) {
// Prevent the submit with preventDefault()
event.preventDefault();
// Do something to check the submit etc.
}
});