Here I have one input field that I want to make mandatory url input field and I done this code.when I put url in input field or put any other text only input field in both case it saves input field and save in database. so, how to make mandatory url type input field in angular 6.
<form method="post" enctype="multipart/form-data">
<mat-form-field>
<input matInput type="url" pattern="https?://.+" placeholder="Large Icon" name="largeicon" #largeicon="ngModel"
[(ngModel)]="notificationObj.largeicon" required>
</mat-form-field>
<div *ngIf="largeicon.errors && (largeicon.dirty || largeicon.touched)" class="alert alert-danger">
<div [hidden]="!largeicon.errors.required">URL is required!</div>
<div [hidden]="!largeicon.errors.pattern">Must be a valid URL!</div>
</div>
<button mat-raised-button (click)="sendNotification()">SEND NOTIFICATION</button>
</form>
On Button click "sendNotification()" you are not checking the validation.
There are many ways to block the method call on validation. Find below sample code.
<button mat-raised-button [disabled]="largeicon.errors && (largeicon.errors.required || largeicon.errors.pattern)" (click)="sendNotification()">SEND NOTIFICATION</button>
Above code will disable button when validation failed.
your pattern should be
pattern="/^(http[s]?:\/\/){0,1}(www\.){0,1}[a-zA-Z0-9\.\-]+\.[a-zA-Z]{2,5}[\.]{0,1}/"
or else on form submit function to check the regex value if matched then true else false
this fiddle will help you to understand better
You have done some mandatory things wrong to work with ngForm in the way as it is designed.
Please take a look at this guide: https://www.concretepage.com/angular-2/angular-2-ngform-with-ngmodel-directive-example
These are the major keys:
Use ngForm at the form tag
use ngSubmit instead of an (click) button, because that bypasses the form
try to add disabled in your form submit button and your already using the required in input field so,it will work now
<form method="post" enctype="multipart/form-data" #ngForm="formName">
<mat-form-field>
<input matInput type="url" pattern="https?://.+" placeholder="Large Icon" name="largeicon" #largeicon="ngModel"
[(ngModel)]="notificationObj.largeicon" required>
</mat-form-field>
<div *ngIf="largeicon.errors && (largeicon.dirty || largeicon.touched)" class="alert alert-danger">
<div [hidden]="!largeicon.errors.required">URL is required!</div>
<div [hidden]="!largeicon.errors.pattern">Must be a valid URL!</div>
</div>
<button mat-raised-button (click)="sendNotification()" [disabled]="!formName.form.valid">SEND NOTIFICATION</button>
</form>
for more details look here in angular docs
Related
I have a button with a (click) event that currently fires a method in an Angular component which works perfectly, but I also need to fire the same method if the user hits the enter key from the input box so the user has a choice.
Here' the HTML I'm using for the input and the button:
<div class="input-group input-group-sm mt-3">
<input autocomplete="off" list="autocompleteOff" type="text" class="form-control" placeholder="E.G. 'What is a beneficary?'" aria-label="Ask" [(ngModel)]="userQuestion" id="userQuestion" name="userQuestion" [ngStyle]="{'background-color': brand?.colours.secondary, 'color': brand?.colours.primary}">
<div class="input-group-append">
<button id="user-btn" class="btn btn-secondary" type="button" (click)="askQuestion()" [ngStyle]="{'background-color': brand?.colours.primary, 'color': brand?.colours.secondary}">Ask</button>
</div>
</div>
Can I do this form the HTML side or do I need to set up a listener for the enter key?
You can use keyup.enter :
<input (keyup.enter)="askQuestion()"/>
You may edit your button element type attribute to type="submit".
This is already answered in Fire a method when click an Enter key
<input ng-keyup="$event.keyCode == 13 ? MyFunc() : null" >
I have this form:
<form method="post">
<input type="tel" name=phone_no required>
<input type="password" name=password required>
<button type="submit">Sign In</button>
</form>
How can I automatically submit this form when browser auto-fills these input fields in form ?
You can do this using Javascript :
(1) Get html elements with selector :
document.getElementsByName(..)
(2) Check if the elements contains any value.
element.value
(3) In that case, trigger an event which click on the submit button :
button.click();
I am working with a simple form:
HTML
<mat-card>
<form (submit)="onAddBet(betForm)" #betForm="ngForm">
<mat-form-field>
<textarea #description="ngModel" matInput rows="6" placeholder="Description" name="description" ngModel
required></textarea>
<mat-error *ngIf="description.invalid">Please enter a Bet Description</mat-error>
</mat-form-field>
<mat-slide-toggle #privacy="ngModel" name="privacy" ngModel>Private</mat-slide-toggle>
<mat-slide-toggle #comments="ngModel" name="comments" ngModel>Allow comments</mat-slide-toggle>
<button mat-raised-button color="primary" type="submit">
CREATE
</button>
</form>
</mat-card>
If I press submit without touching any field of the form I get all the fields empty as it should be expected but I would like to get instead of the status of the form, meaning all the fields as "" but in the fields "privacy" and "comments" as false (boolean) (the default appearance of the toggles is as not marked).
I know that this could be easily done by Typescript from the component following the method:
Typescript
onAddBet(form: NgForm) {
if (!form.value.privacy) {
form.value.privacy = false;
console.log(form.value);
} else console.log(form.value);
if (form.invalid) return;
form.resetForm();
}
But I was wondering if there is any HTML attribute to run the same code avoiding to use Typescript
How could I do it?
You can initialize your ngModel in your HTML by using ngModel with a one-way binding
<mat-slide-toggle #privacy="ngModel" name="privacy" [ngModel]="false">Private</mat-slide-toggle>
<mat-slide-toggle #comments="ngModel" name="comments" [ngModel]="false">Allow comments</mat-slide-toggle>
Then in your component
onAddBet(form: NgForm) {
console.log(form.value);
if (form.invalid) return;
form.resetForm();
}
As per the documentation of slide-toggle you can use [checked]="checked" in HTML.
<input class="form-control" type="text" name="txtSpouseOccupation" id="txtSpouseOccupation" required>
<button type="button" id="next_personal" class="form-control btn-success" style="width:10%" onclick="openTab(event,'dependentTab')">Next</button>
when I click the next button it just goes to the next tab and ignores the required even the inputs are not yet filled up
You can accomplish your need by using this simple attribute required. So below I'll add example;
<html>
<head>
</head>
<body>
<form action="next.php">
<input type="text" required="true">
<input type="submit">
</form>
</body>
</html>
So when you click button to navigate to next page or tab it will show simple message near relevant text box to fill that field.
Though you used tabs you can use this.
In this case, your both elements are independent to each other. You have text/input whose functionality is to take inputs and then there is a submit button whose functionality to do something on click.
Now required will only work if you define a relation between submit button and input/text. <form> elements does that for you as it wraps both elements in it and than the submit button default action is to submit the form, and then before submitting it will check if the input values are assigned as per required=true.
But you trigger a function on the click of it. If you simply want to go to some url by submitting form
Try Form
<form action="your url" method="GET or POST">
<input type= "text" required ="true"/>
<button type = "submit" >next</button>
</form>
OR you can use javascript for it.
function newTab(){
let input = document.getElementById('text-input').value;
if(input === ""){
alert('please fill text')
return;
}
window.location.href = 'http://google.com';
}
<input type= "text" required ="true" id = "text-input"/>
<button type = "submit" onClick = "newTab()" >next</button>
I have worked on AngularJs and now working on Angular2. Whenever I searched for form validation in angular I always found the submit button like below:
In AnglarJs
<input type="submit"
ng-disabled="myForm.user.$dirty && myForm.user.$invalid ||
myForm.email.$dirty && myForm.email.$invalid">
In Angular2
<button type="submit" class="btn btn-default"
[disabled]="!heroForm.form.valid">Submit</button>
But I wanted the submit button should be enable and whenver user click on that we prompt the error below the text fields. There is no exact solution mentioned for this purpose.
I found some of that some of the users directly clicks on submit button and they wanted to fill only required fileds.
This is my observation only may be some of you also experienced the same while development.
For AngularJs 1 I am using custom-submit directive from here
https://gist.github.com/maikeldaloo/5133963
So please suggest me any solution to provide custom-submit in angular2 also.
---- Sample Login Form (Angular2) ---
<form class="ui large form" (ngSubmit)="onUserLogin(loginForm.form.valid)" #loginForm="ngForm" method="post" novalidate>
<sm-loader [complete]="!formSubmited" class="inverted" text="Loading..."></sm-loader>
<div class="field">
<input type="email" name="email" placeholder="Email" [(ngModel)]="login.email" #email="ngModel" required />
<div [hidden]="email.valid || email.pristine" class="error text-left">
Email is required
</div>
</div>
<div class="field">
<input type="password" name="password" placeholder="Password" [(ngModel)]="login.password" #password="ngModel" required />
<div [hidden]="password.valid || password.pristine" class="error text-left">
Password is required
</div>
</div>
<button class="fluid yellow large ui button" type="submit">Login</button>
</form>
Please check what custom-submit directive are doing. Please give me answers the based on that. I know I can check the form valid status on controller level, but why this way I can say only form is not valid, I can not say which field is empty (we can also check this which field is valid, but don't know how to enable the error divs from controllers)
Please refer this...
https://gist.github.com/maikeldaloo/5133963
Thanks,
Just set a state and show/hide the errors depending on the state:
onSubmit() {
if(hasErrors()) {
this.hasErrors = true;
return false; // preventDefault
}
this.postData(); // process submit event
}
<div *ngIf="hasError">
... error info here
</div>
This way we actually validate whether you have entered the correct values or not. If any of the value fails then submit button gets disabled otherwise enabled.
For ex: E-mail : If email id doesn't have # and ., then it will be considered as dirty, which wouldn't lead to enable the submit button.
Edited:
To display the message you can do one thing:
<input type="submit" ng-click="done(heroForm.form.valid)" />
And in controller you can do this way.
$scope.done = function(valid){
if(valid) {
// Form content is valid, process it
} else {
// show error and do nothing.
}
}