Why Is my script freezing up when I hit enter? - forms

The majority of the Add-on is good but whenever I hit enter (which is, in my opinion, the most common way to submit a form, for example, a login form), but all it does is blank out.
I've tried linking the script with a onkeydown like so:
<div onkeydown="handle(event)">blagh blagh blagh</div>
but I still get the same results:
<html>
<form id='myForm' style="font-family:Georgia;">
<table>
<tr><td><h2>Enter your Password</h2></td></tr>
<tr><td><p>DO NOT HIT ENTER ON YOUR KEYBOARD!!!!!</p></td></tr>
<tr><td><input name='password' type='password' value="" onkeypress="handle(event)"></td></tr>
<tr><td><div id="submitbuttcontainer"><img id="submitloader" style="display:none;" src='https://lh6.googleusercontent.com/-S87nMBe6KWE/TuB9dR48F0I/AAAAAAAAByQ/0Z96LirzDqg/s27/load.gif' /><input id="submitbutt" type='button' onclick='showWorking();google.script.run.withSuccessHandler(onSuccess).decodeForRequest(document.getElementById("myForm"));' name="Submit" value="Submit"></div></td></tr>
</table>
</form>
<script>
function onSuccess(obj) {
document.getElementById('submitbutt').style.display="block";
document.getElementById('submitloader').style.display="none";
if(obj.status == 'success') {
google.script.host.closeDialog();
browser.msgbox('Access Granted', browser.buttons.OK)
}
else {
browser.msgbox('ALERT!!','!OOF!','Incorrect Password. Please retry', browser.buttons.OK);
}
}
function showWorking() {
document.getElementById('submitbutt').style.display="none";
document.getElementById('submitloader').style.display="block";
}
function handle(e){
if(e.keyCode === 13)
document.getElementById('submitbuttcontainer').click();
}
</script>
</html>
All I'm trying to do is get the form to submit when I hit enter and not blank out. I always hit enter to submit a form but in this case all it does is blank out the form and all I have is whiteness.
Here's the link for the complete source code (don't know if this will work because I'm in a school district):
https://script.google.com/a/bcsdschools.net/d/1_YUx4ZP3qEWVcFMc-MvfEYX2S34r7-b4M0iRlE_JQa81T3ZubN5OeISa/edit)

Problem
Hitting enter key results in form submission (which is explicitly forbidden in Apps Script due to its client-to-server communication implementation).
Solution 1 - handle inputs individually
Add preventDefault() to a keydown event if key is enter (btw, keypress event is deprecated, see reference on MDN, use the keydown / keyup instead):
var ENTER_CODE = 13;
function handle(e) {
if(e.keyCode === ENTER_CODE) {
e.preventDefault();
document.getElementById('submitbuttcontainer').click();
}
}
Solution 2 - handle form submit
You can listen for a submit event on your form instead and invoke preventDefault() as the only statement in event handler or handle form submission at the same time if you expect form to be submitted on enter key hit:
//assumption: form is initiated elsewhere in code;
form.addEventListener('submit', (event) => {
event.preventDefault();
//handle submission;
});
You can also prevent all forms from being submitted to make the setup flexible:
(() => {
const { forms } = document;
Object.values(forms).forEach(
form => form.addEventListener("submit", (e) => e.preventDefault())
);
})();
Or, alternatively, use event delegation and register one listener on the document since the event bubbles up:
document.addEventListener("submit", (e) => e.preventDefault());
Suggestion
Please, use addEventListener instead of on[event name here] attributes. This way is much more flexible and has the benefit of being concise and easy for others to read.
References
Handling forms in Apps Script guide
Why use addEventListener? MDN reference

I wanted to try to give you a complete answer, but I have to admit that I may know less about event handlers than you. But this seems to work for me.
aq4.html:
<html>
<head>
<script>
window.onload=function() {
preventFormSubmit1();
}
function preventFormSubmit1() {
console.log('preventFormSubmit1');
var form=document.forms['myForm'];
form.addEventListener('submit',function(e) {
e.preventDefault();
});
}
function handleFormSubmit(formObject) {
console.log('handleFormSubmit');
var first=document.forms['myForm']['first'].value;
var last=document.forms['myForm']['last'].value
var sheet=document.forms['myForm']['sheet'].value;
console.log('%s,%s,%s',first,last,sheet);
if(first.length>0 && last.length>0 && sheet.length>0) {
google.script.run
.withSuccessHandler(function(msg){
var div=document.getElementById('output');
div.innerHTML=msg;
var inputs=document.querySelectorAll('input[type=text]');
inputs[0].focus();
for(var i=0;i<inputs.length;i++) {
inputs[i].value='';
}
})
.processForm(formObject);
}else{
alert("Invalid or Incomplete Data");
}
}
console.log("MyCode");
</script>
</head>
<body>
<form id="myForm" onsubmit="handleFormSubmit(this)">
<input type="text" name="first" /> First<br />
<input type="text" name="last" /> Last<br />
<select name="sheet">
<option value="Sheet1">Sheet1</option>
<option value="Sheet2">Sheet2</option>
</select> Sheet<br />
<input id="sub" type="submit" value="Submit" />
</form>
<div id="output"></div>
</body>
</html>
aq1.gs:
function processForm(formObject) {
var ss=SpreadsheetApp.getActive();
var sh=ss.getSheetByName(formObject.sheet);
sh.appendRow([formObject.first,formObject.last]);
return Utilities.formatString('First: %s<br />Last: %s<br />Sheet: %s', formObject.first,formObject.last,formObject.sheet);
}
function runOne() {//This loads the dialog
var userInterface=HtmlService.createHtmlOutputFromFile('aq4').setWidth(1000);
SpreadsheetApp.getUi().showModelessDialog(userInterface, "My Form Example")
}

Related

Use two buttons in the same form for invisible recaptcha

I'm trying to implement the new invisible recaptcha, from Google.
It's all working perfectly, but my forms always have two submit buttons, that does different things with the input.
I tried to simply add another in my form, but google only recognize the first one in code.
I can't think of any reason that would prevent the other button to work properly. Here is a simple example of what I tried :
<form action="page.php" method="POST">
<input type="text" value="textfield"/><br/>
<button class="g-recaptcha" data-sitekey="mysitekey" data-callback='onSubmit' value="anaction">An action</button>
<button class="g-recaptcha" data-sitekey="mysitekey" data-callback='onSubmit' value="anotheraction">Another action</button>
</form>
I usually tell apart the two buttons by making an isset on the POST values. Here it doesn't seem to work with the second button. If I switch the two lines, it will make the other button submit properly.
If someone has an idea about this, I'll thank him for enlightments.
Thank you :)
I had same issue and I fixed it like below:
<button type="submit" class="g-recaptcha"
id="captcha1"
data-sitekey="YOUR_SECRETKEY"
data-callback="sendData">button</button>
<button type="submit" class="g-recaptcha"
id="captcha2"
data-sitekey="YOUR_SECRETKEY"
data-callback="sendData">button</button>
<script type="text/javascript">
$( document ).ready(function() {
$(".g-recaptcha").each(function() {
var object = $(this);
grecaptcha.render(object.attr("id"), {
"sitekey" : "YOUR_SITEKEY",
"callback" : function(token) {
object.parents('form').find(".g-recaptcha-response").val(token);
object.parents('form').submit();
}
});
});
}
);
</script>
Yes I created a function sendData like below:
<script type="text/javascript">
function sendData(){
var test = $("#test").val();
if(test != ""){
$.post( "page.php",
{ 'g-recaptcha-response': grecaptcha.getResponse(), 'test' : test})
.done(function( data ) {
console.log(data);
}
);
}else{
console.log(data);
}
grecaptcha.reset(); //important
}
</script>
Stash the token in a hidden field and use it instead of the g-recaptcha-response value to send your verification request. You can distinguish between the two submissions by saving the action item in the JSON return object. I have no idea why this works, by the way.
<head>
...
<script src="https://www.google.com/recaptcha/api.js"></script>
<script>
function onSubmit(token) {
document.getElementById("token").value = token;
document.getElementById("form").submit();
}
</script>
...
</head>
<body>
...
<form id="form" action="page.php" method="POST">
<input type="hidden" id="token" name="token">
...
<button type="submit" class="g-recaptcha" data-sitekey="..." data-callback="onSubmit" data-action="action">An Action</button>
<button type="submit" class="g-recaptcha" data-sitekey="..." data-callback="onSubmit" data-action="anotheraction">Another Action</button>
</form>

How to scroll to error in form?

I have just started using AngularJS, I would like to know this approach to scroll the page to the first input with an error when I submit a form.
Here is the way with jQuery :
$('html, body').animate({
scrollTop: $("--- #ID OF THE FIRST INPUT WITH ERROR ---").offset().top
}, 2000);
How to do this in Angular ?
HTML
<form class="form" novalidate>
<input type="text" class="nom-du-projet" ng-model="fields.nom" required />
<p ng-show="fields.nom.$invalid && !fields.nom.$pristine">The name is required.</p>
<input type="text" ng-model="fields.cible" />
...
<button type="submit" ng-click="submit(fields)">Add</button>
</form>
JS
$scope.submit = function(fields){
console.log(fields);
$http
.post('/xxxx', fields)
.success(function(response) {
// success
})
.error(function(response) {
// scroll to field error
});
}
You could use the $anchorScroll service.
$location.hash("<errorFieldID>");
$anchorScroll();
Or you could just use:
$window.scrollTo //you could even get bold and user window.scrollTo
There are a couple plugins out there that say they can do it.. but I unfortunately have not vetted them so I can't recommend any.
You could try something like this:
//scroll to an anchor by ID
$scope.scrollToAnchor = function (anchor) {
if (anchor !== null) {
$location.hash(anchor);
$anchorScroll(anchor);
}
}
//use above function
$scope.scrollToAnchor($scope.myForm.$error.required[0].$name);
//or any ID
$scope.scrollToAnchor('ID');
I have a written a angularJS directive for the same purpose, you can include the directive as bower component and use this functionality without having to write any extra code for any form in your application. Please do let me know, if any improvements or corrections/enhancements are needed for the directive.
https://github.com/udayvarala/ng-scroll-to-error
Thanks,

Backbone.js and form input blur

I am pretty much a backbonejs newbie. I am submitting form data to mysql.
I have one special input box where the use types in his or her email address as a user name.
As it stands, I can check all my input fields (user, pass, address, phone, etc) client
side, use an event on a button, load the model, use PHP to put the data into the db.
This works just fine and is tested. The backend validation works fine and feeds to
the browser when necessary.
Now I want to check the loginname field against the back end BEFORE writing the record (I know I can trap this on the back end in the final submit but want to do it here). If the user already has an account with the same email address I want to catch that client side. The issue is I can't seem to find a way to capture this blur (or onblur or change whatever I use) when I move off the loginname field so I can (in the render of the view is all I can figure) go off, use PHP again and send back a flag "new" or "existing"
No errors in Google developer tool
define([
'jquery',
'underscore',
'backbone',
'lib/jquery-migrate-1.2.1',
'models/RegisterModel',
'text!templates/RegisterTemplate.html',
'lib/jquery.maskedinput-1.0',
'lib/bootstrap-acknowledgeinput.min',
'lib/jqBootstrapValidation'
], function($, _, Backbone, jQueryMigrate, RegisterModel, RegisterTemplate,
MaskedInput,Ack, jqAck){
var RegisterView = Backbone.View.extend({
el: $("#container"),
events: {
'click .btn-primary': 'saveClient',
'focusout .loginname': 'usercheck'
},
usercheck: function() { //** not working
console.log("usercheck detected");
alert("Alerts suck.");
},
render: function(){
//Since our template has dynamic variables in it, we need to compile it
var compiledTemplate = _.template( RegisterTemplate, this.model );
this.$el.html(compiledTemplate); //Replaces EVERYTHING inside the <div
id="container">
this.$('#phone').mask('(999) 999-9999');
this.$('#phone2').mask('(999) 999-9999');
this.$('#zip').mask('99999');
$(function () { //** working
$("input,select,textarea").not("[type=submit]").jqBootstrapValidation();
});
$('.loginname').live("click", function () { //** not working
alert('AHHHHHH!');
});
$().acknowledgeinput({ // ** this works fine
success_color: '#00FF00',
danger_color: '#FF0000',
update_on: 'keyup'
});
** I looked in Chrome at the blur event for the input with name/id = loginname
HTML I did look at the blur for the elmement with id (Chrome says it's input#loginname)
does have the blur event attached to it. I changed my code a bit, but still it doesn't seem to trigger. I never know with backbone if it's just something simple or one of those
"this and scope" issues :)
<div id="container" class="row-fluid">
<div class="span6">
<div class="requiredNotice"><i class="icon-warning-sign icon-red"></i> Can't
be blank!</div>
<h3>New Client Registration:</h3>
<form class="form-horizontal" method="POST">
<fieldset>
<div class="control-group">
<label class="control-label required" for="loginname">UserID (Email
</label>
<div class="controls">
<div class="input-prepend" data-role="acknowledge-input">
<div data-role="acknowledgement"><i></i></div>
<input type="email" data-type="email" required="required"
placeholder="Use email account"
maxlength="254" name="loginname" id="loginname"
class="inputclass pageRequired
input-xlarge" />
</div>
<span class="loginname_error label label-info hide"></span>
</div>
</div> ... etc
events: {
'click .btn-primary' : 'saveClient',
'focusout #input.loginname' : 'userCheck'
// "blur input.loginname" : "userCheck"
},
userCheck: function(e) {
console.log("usercheck detected");
alert("Alerts suck.");
},
.live is not needed here, there is nothing wrong with your event hash as well. There could be some thing wrong with template. I did just isolate the input field and focusout event in this jsfiddle it's working fine.
<script type="text/template" id="formtemplate">
<form>
<input type="text" class="loginname" value="" placeholder="enter login"/>
</form>
</script>
...
var View = Backbone.View.extend({
events:{
'focusout .loginname':'checkUser'
},
render:function(){
this.$el.html($('#formtemplate').html());
},
checkUser:function(e){
alert('checkUser'); //works well
}
});
var view = new View();
view.render();
view.$el.appendTo('body');
Okay - you said to tie this to blur, and this format finally worked!
'blur input#loginname' : 'userCheck'
events: {
'click .btn-primary' : 'saveClient',
'blur input#loginname' : 'userCheck'
},
userCheck: function(e) {
console.log("usercheck detected");
alert("Alerts suck.");
},
The console is not showing up, but at least I'm trapping the blur now! Thanks eveyone.

submiting form on div click with js

I have a div element and I want that when I click on it i submit a form which is hidden.
div code
<div class="a15 training-exercise">
some text
<form accept-charset="UTF-8" action="/trainings/1/training_exercises/5" data-remote="true" method="post"><div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="✓"><input name="_method" type="hidden" value="put"></div>
<input id="training_exercise_done" name="training_exercise[done]" type="text" value="false">
<input name="commit" type="submit" value="subit">
</form>
</div>
coffescript
$ ->
$('.training-exercise').click ->
if $(this).hasClass('done')
$(this).removeClass('done')
$(this).find('input:text').val(false)
$(this).closest("form").submit()
else
$(this).addClass('done')
$(this).find('input:text').val(true)
$(this).closest('form').submit()
corresponding JS code
$(function() {
return $('.training-exercise').click(function() {
if ($(this).hasClass('done')) {
$(this).removeClass('done');
$(this).find('input:text').val(false);
return $(this).closest("form").submit;
} else {
$(this).addClass('done');
$(this).find('input:text').val(true);
return $(this).closest('form').submit;
}
});
});
i didn't put checkbox for true and false because f.checkbox gave me some strange results
The problem here is:
1) Everything is happening except form submitting
2) form has visibility: hidden; and it is hidden, but there is empty space where the form is, I want that it looks like there is nothing there
For 1st problem, try
$(function() {
$('.training-exercise').click(function() {
var element = $(this);
if (element.hasClass('done')) {
element.removeClass('done');
element.find('input:text').val(false);
element.closest('form').submit(); //<-- brackets here.
} else {
element.addClass('done');
element.find('input:text').val(true);
element.closest('form').submit();
}
});
});
For 2nd problem use display:none; instead of visibility:hidden.
It seems that form selecting didn't work (although it work when I tried from console)
The solution that works is:
$(this).find('input:submit').submit()

Trigger validation of all fields in Angular Form submit

I'm using this method: http://plnkr.co/edit/A6gvyoXbBd2kfToPmiiA?p=preview to only validate fields on blur. This works fine, but I would also like to validate them (and thus show the errors for those fields if any) when the user clicks the 'submit' button (not a real submit but a data-ng-click call to a function)
Is there some way to trigger validation on all the fields again when clicking that button?
What worked for me was using the $setSubmitted function, which first shows up in the angular docs in version 1.3.20.
In the click event where I wanted to trigger the validation, I did the following:
vm.triggerSubmit = function() {
vm.homeForm.$setSubmitted();
...
}
That was all it took for me. According to the docs it "Sets the form to its submitted state." It's mentioned here.
I know, it's a tad bit too late to answer, but all you need to do is, force all forms dirty. Take a look at the following snippet:
angular.forEach($scope.myForm.$error.required, function(field) {
field.$setDirty();
});
and then you can check if your form is valid using:
if($scope.myForm.$valid) {
//Do something
}
and finally, I guess, you would want to change your route if everything looks good:
$location.path('/somePath');
Edit: form won't register itself on the scope until submit event is trigger. Just use ng-submit directive to call a function, and wrap the above in that function, and it should work.
In case someone comes back to this later... None of the above worked for me. So I dug down into the guts of angular form validation and found the function they call to execute validators on a given field. This property is conveniently called $validate.
If you have a named form myForm, you can programmatically call myForm.my_field.$validate() to execute field validation. For example:
<div ng-form name="myForm">
<input required name="my_field" type="text" ng-blur="myForm.my_field.$validate()">
</div>
Note that calling $validate has implications for your model. From the angular docs for ngModelCtrl.$validate:
Runs each of the registered validators (first synchronous validators and then asynchronous validators). If the validity changes to invalid, the model will be set to undefined, unless ngModelOptions.allowInvalid is true. If the validity changes to valid, it will set the model to the last available valid $modelValue, i.e. either the last parsed value or the last value set from the scope.
So if you're planning on doing something with the invalid model value (like popping a message telling them so), then you need to make sure allowInvalid is set to true for your model.
You can use Angular-Validator to do what you want. It's stupid simple to use.
It will:
Only validate the fields on $dirty or on submit
Prevent the form from being submitted if it is invalid
Show custom error message after the field is $dirty or the form is submitted
See the demo
Example
<form angular-validator
angular-validator-submit="myFunction(myBeautifulForm)"
name="myBeautifulForm">
<!-- form fields here -->
<button type="submit">Submit</button>
</form>
If the field does not pass the validator then the user will not be able to submit the form.
Check out angular-validator use cases and examples for more information.
Disclaimer: I am the author of Angular-Validator
Well, the angular way would be to let it handle validation, - since it does at every model change - and only show the result to the user, when you want.
In this case you decide when to show the errors, you just have to set a flag:
http://plnkr.co/edit/0NNCpQKhbLTYMZaxMQ9l?p=preview
As far as I know there is a issue filed to angular to let us have more advanced form control. Since it is not solved i would use this instead of reinventing all the existing validation methods.
edit: But if you insist on your way, here is your modified fiddle with validation before submit. http://plnkr.co/edit/Xfr7X6JXPhY9lFL3hnOw?p=preview
The controller broadcast an event when the button is clicked, and the directive does the validation magic.
One approach is to force all attributes to be dirty. You can do that in each controller, but it gets very messy. It would be better to have a general solution.
The easiest way I could think of was to use a directive
it will handle the form submit attribute
it iterates through all form fields and marks pristine fields dirty
it checks if the form is valid before calling the submit function
Here is the directive
myModule.directive('submit', function() {
return {
restrict: 'A',
link: function(scope, formElement, attrs) {
var form;
form = scope[attrs.name];
return formElement.bind('submit', function() {
angular.forEach(form, function(field, name) {
if (typeof name === 'string' && !name.match('^[\$]')) {
if (field.$pristine) {
return field.$setViewValue(field.$value);
}
}
});
if (form.$valid) {
return scope.$apply(attrs.submit);
}
});
}
};
});
And update your form html, for example:
<form ng-submit='justDoIt()'>
becomes:
<form name='myForm' novalidate submit='justDoIt()'>
See a full example here: http://plunker.co/edit/QVbisEK2WEbORTAWL7Gu?p=preview
Here is my global function for showing the form error messages.
function show_validation_erros(form_error_object) {
angular.forEach(form_error_object, function (objArrayFields, errorName) {
angular.forEach(objArrayFields, function (objArrayField, key) {
objArrayField.$setDirty();
});
});
};
And in my any controllers,
if ($scope.form_add_sale.$invalid) {
$scope.global.show_validation_erros($scope.form_add_sale.$error);
}
Based on Thilak's answer I was able to come up with this solution...
Since my form fields only show validation messages if a field is invalid, and has been touched by the user I was able to use this code triggered by a button to show my invalid fields:
// Show/trigger any validation errors for this step
angular.forEach(vm.rfiForm.stepTwo.$error, function(error) {
angular.forEach(error, function(field) {
field.$setTouched();
});
});
// Prevent user from going to next step if current step is invalid
if (!vm.rfiForm.stepTwo.$valid) {
isValid = false;
}
<!-- form field -->
<div class="form-group" ng-class="{ 'has-error': rfi.rfiForm.stepTwo.Parent_Suffix__c.$touched && rfi.rfiForm.stepTwo.Parent_Suffix__c.$invalid }">
<!-- field label -->
<label class="control-label">Suffix</label>
<!-- end field label -->
<!-- field input -->
<select name="Parent_Suffix__c" class="form-control"
ng-options="item.value as item.label for item in rfi.contact.Parent_Suffixes"
ng-model="rfi.contact.Parent_Suffix__c" />
<!-- end field input -->
<!-- field help -->
<span class="help-block" ng-messages="rfi.rfiForm.stepTwo.Parent_Suffix__c.$error" ng-show="rfi.rfiForm.stepTwo.Parent_Suffix__c.$touched">
<span ng-message="required">this field is required</span>
</span>
<!-- end field help -->
</div>
<!-- end form field -->
Note: I know this is a hack, but it was useful for Angular 1.2 and earlier that didn't provide a simple mechanism.
The validation kicks in on the change event, so some things like changing the values programmatically won't trigger it. But triggering the change event will trigger the validation. For example, with jQuery:
$('#formField1, #formField2').trigger('change');
I like the this approach in handling validation on button click.
There is no need to invoke anything from controller,
it's all handled with a directive.
on github
You can try this:
// The controller
$scope.submitForm = function(form){
//Force the field validation
angular.forEach(form, function(obj){
if(angular.isObject(obj) && angular.isDefined(obj.$setDirty))
{
obj.$setDirty();
}
})
if (form.$valid){
$scope.myResource.$save(function(data){
//....
});
}
}
<!-- FORM -->
<form name="myForm" role="form" novalidate="novalidate">
<!-- FORM GROUP to field 1 -->
<div class="form-group" ng-class="{ 'has-error' : myForm.field1.$invalid && myForm.field1.$dirty }">
<label for="field1">My field 1</label>
<span class="nullable">
<select name="field1" ng-model="myresource.field1" ng-options="list.id as list.name for list in listofall"
class="form-control input-sm" required>
<option value="">Select One</option>
</select>
</span>
<div ng-if="myForm.field1.$dirty" ng-messages="myForm.field1.$error" ng-messages-include="mymessages"></div>
</div>
<!-- FORM GROUP to field 2 -->
<div class="form-group" ng-class="{ 'has-error' : myForm.field2.$invalid && myForm.field2.$dirty }">
<label class="control-label labelsmall" for="field2">field2</label>
<input name="field2" min="1" placeholder="" ng-model="myresource.field2" type="number"
class="form-control input-sm" required>
<div ng-if="myForm.field2.$dirty" ng-messages="myForm.field2.$error" ng-messages-include="mymessages"></div>
</div>
</form>
<!-- ... -->
<button type="submit" ng-click="submitForm(myForm)">Send</button>
I done something following to make it work.
<form name="form" name="plantRegistrationForm">
<div ng-class="{ 'has-error': (form.$submitted || form.headerName.$touched) && form.headerName.$invalid }">
<div class="col-md-3">
<div class="label-color">HEADER NAME
<span class="red"><strong>*</strong></span></div>
</div>
<div class="col-md-9">
<input type="text" name="headerName" id="headerName"
ng-model="header.headerName"
maxlength="100"
class="form-control" required>
<div ng-show="form.$submitted || form.headerName.$touched">
<span ng-show="form.headerName.$invalid"
class="label-color validation-message">Header Name is required</span>
</div>
</div>
</div>
<button ng-click="addHeader(form, header)"
type="button"
class="btn btn-default pull-right">Add Header
</button>
</form>
In your controller you can do;
addHeader(form, header){
let self = this;
form.$submitted = true;
...
}
You need some css as well;
.label-color {
color: $gray-color;
}
.has-error {
.label-color {
color: rgb(221, 25, 29);
}
.select2-choice.ui-select-match.select2-default {
border-color: #e84e40;
}
}
.validation-message {
font-size: 0.875em;
}
.max-width {
width: 100%;
min-width: 100%;
}
To validate all fields of my form when I want, I do a validation on each field of $$controls like this :
angular.forEach($scope.myform.$$controls, function (field) {
field.$validate();
});