Onclick form is not validating - html

I'm creating form which has Name, Email, Password fields. My code is mentioned below
signup.html
<form class="form-horizontal form-material" id="loginform" [formGroup]="registrationform" novalidate>
<h3 class="box-title m-b-20">Sign Up</h3>
<div class="form-group">
<div class="col-xs-12">
<input class="form-control" required="" type="text" placeholder="Name" formControlName="name">
</div>
</div>
<div *ngIf="registrationform.controls['name'].invalid && (registrationform.controls['name'].dirty )" class="alert alert-danger">
<div *ngIf="registrationform.controls['name'].errors.required">
Name should consist 3 Characters
</div>
</div>
<div class="form-group ">
<div class="col-xs-12">
<input class="form-control" required="" type="text" placeholder="Email" formControlName="email">
</div>
</div>
<div *ngIf="registrationform.controls['email'].invalid && (registrationform.controls['email'].dirty )" class="alert alert-danger">
<div *ngIf="registrationform.controls['email'].errors.required">
Please Enter Valid Email
</div>
</div>
<div class="form-group ">
<div class="col-xs-12">
<show-hide-password size="md" icon="entypo">
<input type="password" name="password" placeholder="Password" formControlName="password">
</show-hide-password>
<!-- <input class="form-control" required="" type="password" placeholder="Password"> -->
<!-- <button (click)="x.type=x.type=='password'?'text':'password'">Show password</button> -->
</div>
</div>
<div *ngIf="registrationform.controls['password'].invalid && (registrationform.controls['password'].dirty )" class="alert alert-danger">
<div *ngIf="registrationform.controls['password'].errors.required">
Name should consist 3 Characters
</div>
</div>
<div class="form-group text-center p-b-20">
<div class="col-xs-12">
<!-- <a [routerLink]="['/authentication/login']" class="btn btn-info btn-lg btn-block btn-rounded text-uppercase waves-effect waves-light">Sign Up</a> -->
<button type="submit" class="btn btn-info btn-lg btn-block btn-rounded text-uppercase waves-effect waves-light">Sign Up</button>
</div>
</div>
<div class="form-group m-b-0">
<div class="col-sm-12 text-center">
Already have an account?
<a class="text-info m-l-5" [routerLink]="['/authentication/login']">
<b>Sign In</b>
</a>
</div>
</div>
</form>
and my signup.ts is below
export class Signup2Component implements OnInit {
registrationform: FormGroup;
emailPattern = "^[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,4}$";
constructor(private form: FormBuilder) {
// this.emailPattern = "^[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,4}$";
this.registrationFormValidation();
}
ngOnInit() { }
registrationFormValidation() {
this.registrationform = this.form.group({
name: ['', Validators.compose([Validators.required, Validators.minLength(3)])],
email: ['', Validators.compose([Validators.required, Validators.pattern(this.emailPattern)])],
password: ['', Validators.compose([Validators.required, Validators.minLength(5)])]
// password:['',Validators.required,Validators.minLength(5)]
})
}
}
Once I click on signup button without entering the data in filed it is not validating, even I check in console also. But When enter I data in the field and removed the data it shows error.
But My intention once I click on signup button it should validate everything

If you want to show error on Submit Try this way
registrationform: FormGroup;
submitted=false;
emailPattern = "^[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,4}$";
constructor(private form: FormBuilder) {
// this.emailPattern = "^[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,4}$";
this.registrationFormValidation();
}
ngOnInit() { }
registrationFormValidation() {
this.registrationform = this.form.group({
name: ['', Validators.compose([Validators.required, Validators.minLength(3)])],
email: ['', Validators.compose([Validators.required, Validators.pattern(this.emailPattern)])],
password: ['', Validators.compose([Validators.required, Validators.minLength(5)])]
// password:['',Validators.required,Validators.minLength(5)]
})
}
onSubmit(){
this.submitted=true;
}
Example:https://stackblitz.com/edit/angular-6-reactive-form-validation-cbsncp

You have need to check the touch property
<div *ngIf="registrationform.controls['email'].touched && registrationform.controls['email'].invalid" class="fx-validation-error">
<div *ngIf="registrationform.controls['email'].errors.required">
Please Enter Valid Email
</div>
</div>
You should need to submit form like this
<form [formGroup]="form" (ngSubmit)="save()">
<div class="row">
<div class="form-group col-12">
<button type="submit" class="fx-btn-primary pull-right" [disabled]="!form.valid">Add</button>
</div>
</div>
<div class="row">
<div class="col-4">
<div class="form-group">
<label for="name" class="fx-form-label">
<span class="fx-required">* </span>Name</label>
<input type="text" formControlName="name" id="name" name="name" class="form-control fx-form-control" autocomplete="off">
<div *ngIf="name.touched && name.invalid" class="fx-validation-error">
<div *ngIf="name.errors.required">Name field is required.</div>
</div>
</div>
</div>
</div>
</form>

Related

Unable to submit form by using #submit in vue 3

I encountered a issue using the vuejs #submit.prevent in my login form. When I clicked the login button it doesn't work in my website. And I did the catch error in the function but the console still show nothing. Please help. What I trying to do is when the clicking the form then it will submit the value to my login() function in methods and it will call my laravel back-end API for validate the user information.
Here is the following code below:
<template>
<section class="container mt-3">
<div class="row content d-flex justify-content-center align-items-center">
<div class="col-md-5">
<div class="box shadow bg-white p-4">
<h3 class="mb-4 text-center fs-1">Login Form</h3>
<form #submit.prevent="login()" class="mb-3">
<div class="form-floating mb-3">
<input type="email" class="form-control rounded-0" v-model="form.email" id="floatingInput" placeholder="name#email.com">
<label for="floatingInput">Email</label>
</div>
<div class="form-floating ">
<input type="password" class="form-control rounded-0" v-model="form.password" id="floatingPassword" placeholder="password">
<label for="floatingPassword">Password</label>
</div>
<div class="form-check mb-3">
<input type="checkbox" id="autoSizingCheck2" class="form-check-input">
<label class="form-check-label">Remember me</label>
</div>
<div class="d-grid gap-2 mb-3">
<button type="button" class="btn btn-dark btn-lg border-0 rounded-0">
Login
</button>
</div>
<div class="forgot-password-link mb-3 text-right">
<router-link to="#" title="Forgot Password" class="text-decoration-none">
Forgot Passowrd?
</router-link>
</div>
<div class="forgot-password-link mb-3 text-right">
<router-link to="register" title="Forgot Password" class="text-decoration-none">
Don't have an accounts?
</router-link>
</div>
<div class="sign-up-accounts">
<p class="text-center">
Or Sign up with
</p>
<div class="social-accounts d-flex justify-content-center">
<i class="fa fa-facebook"></i>
<i class="fa fa-google"></i>
</div>
</div>
</form>
</div>
</div>
</div>
</section>
</template>
<script>
import store from '../store';
import router from '../router';
export default {
name:'Login',
data(){
return {
form:{
email:'',
password:''
},
}
},
methods: {
login() {
store.dispatch('login', this.form)
.then(res=>{
router.push('/');
}).catch(error=>{
console.log(error);
});
},
}
}
</script>
<style scoped>
</style>`````
Here is the store file:
state:{
user:{
data:{},
token:sessionStorage.getItem("Token"),
}
},
actions:{
login({commit}, user){
axiosClient.post('/login', {email:user.data.email, password:user.data.password})
.then(res=>{
console.log(res.data.token);
console.log(res);
res.data.email = user.email;
res.data.password = user.password;
commit('authUsers', res);
})
},
mutations:
authUsers: (state, userData)=> {
state.user.data = userData.data.email;
state.user.token = userData.data.token;
console.log(userData);
sessionStorage.setItem('Token', userData.data.token);
sessionStorage.setItem('Email', userData.data.email);
},
This issue was solved by remove a type="button" in the login button

ERROR DOMException: Failed to execute 'setAttribute' on 'Element': 'novalidate(ngSubmit)' is not a valid attribute name

thanks for your help.
The console throws me the next error.
ERROR DOMException: Failed to execute 'setAttribute' on 'Element': 'novalidate(ngSubmit)' is not a valid attribute name.
I´m using Angular for this website.enter image description here
It´s the problem the novalidate() directive?
I do not know what to do, thanks for your time.
import { Component, OnInit } from '#angular/core';
import { NgForm } from '#angular/forms';
import { Order } from 'src/Model/order.model';
import { OrderRepository } from 'src/Model/order.repository';
#Component({
templateUrl: './chech-out.component.html',
//styleUrls: ['./chech-out.component.css']
})
export class ChechOutComponent implements OnInit {
orderSent:boolean=false;
submitted:boolean=false;
constructor(public repository: OrderRepository,
public order: Order)
{
}
ngOnInit(): void {
}
submitOrder(form: NgForm)
{
this.submitted=true;
if(form.valid)
{
this.repository.saveOrder(this.order)
.subscribe(order =>{
this.order.clear();
this.orderSent=true;
this.submitted=false;
})
}
}
}
import { Component, OnInit } from '#angular/core';
import { NgForm } from '#angular/forms';
import { Order } from 'src/Model/order.model';
import { OrderRepository } from 'src/Model/order.repository';
#Component({
templateUrl: './chech-out.component.html',
//styleUrls: ['./chech-out.component.css']
})
export class ChechOutComponent implements OnInit {
orderSent:boolean=false;
submitted:boolean=false;
constructor(public repository: OrderRepository,
public order: Order)
{
}
ngOnInit(): void {
}
submitOrder(form: NgForm)
{
this.submitted=true;
if(form.valid)
{
this.repository.saveOrder(this.order)
.subscribe(order =>{
this.order.clear();
this.orderSent=true;
this.submitted=false;
})
}
}
}
input.ng-dirty.ng-invalid
{
border: 2px solid #ff0000;
}
input.ng-dirty.ng-valid
{
border: 2px solid #6bc502;
}
<div class="container-fluid">
<div class="row">
<div class="col bg-dark text-white">
<a class="navbar-brand" routerLink="/store">
Online Store
</a>
</div>
</div>
</div>
<div *ngIf="orderSent" class="m-2 text-center">
<h2>Thanks!</h2>
<p > Thank you for your order </p>
<p>Well send your order as soon as possible</p>
<button class="btn btn-primary" routerLink="/store">
Return to Store
</button>
</div>
<!--FORM-->
<form *ngIf="!orderSent" #form="ngForm" novalidate(ngSubmit)="submitOrder(form)" class="m-2">
<!--Name-->
<div class="form-group">
<label>Name</label>
<input class="form-control" #name="ngModel" name="name"
[(ngModel)]="order.name" required/>
<span *ngIf="submitted && name.invalid"
class="text-danger">
Please enter your name
</span>
</div>
<!--Address-->
<div class="form-group">
<label>Address</label>
<input class="form-control" #address="ngModel" name="address"
[(ngModel)]="order.address" required/>
<span *ngIf="submitted && address.invalid"
class="text-danger">
Please enter your Address
</span>
</div>
<!--City-->
<div class="form-group">
<label>City</label>
<input class="form-control" #city="ngModel" name="city"
[(ngModel)]="order.city" required/>
<span *ngIf="submitted && city.invalid"
class="text-danger">
Please enter your City
</span>
</div>
<!--State-->
<div class="form-group">
<label>State</label>
<input class="form-control" #state="ngModel" name="state"
[(ngModel)]="order.state" required/>
<span *ngIf="submitted && state.invalid" class="text-danger">
Please enter your State
</span>
</div>
<!--Zip-->
<div class="form-group">
<label>ZIP Postal Code</label>
<input class="form-control" #zip="ngModel" name="zip"
[(ngModel)]="order.zip" required/>
<span *ngIf="submitted && zip.invalid" class="text-danger">
Please enter your Zip Code
</span>
</div>
<!--Country-->
<div class="form-group">
<label>Country</label>
<input class="form-control" #country="ngModel" name="country"
[(ngModel)]="order.country" required/>
<span *ngIf="submitted && country.invalid" class="text-danger">
Please enter your Country
</span>
</div>
<!--Complete Order-->
<div class="text-center">
<!--Button Back-->
<button class]="btn btn primary m-1" routerLink="/cart">
Back
</button>
<!--Button Back-->
<button class="btn- btn-primary m-1" type="submit">
Complete Order
</button>
</div>
<!--Complete Order-->
</form>
<!--FORM-->
input.ng-dirty.ng-invalid
{
border: 2px solid #ff0000;
}
input.ng-dirty.ng-valid
{
border: 2px solid #6bc502;
}
And here is my code.
<div class="container-fluid">
<div class="row">
<div class="col bg-dark text-white">
<a class="navbar-brand" routerLink="/store">
Online Store
</a>
</div>
</div>
</div>
<div *ngIf="orderSent" class="m-2 text-center">
<h2>Thanks!</h2>
<p > Thank you for your order </p>
<p>Well send your order as soon as possible</p>
<button class="btn btn-primary" routerLink="/store">
Return to Store
</button>
</div>
<!--FORM-->
<form *ngIf="!orderSent" #form="ngForm" novalidate(ngSubmit)="submitOrder(form)" class="m-2">
<!--Name-->
<div class="form-group">
<label>Name</label>
<input class="form-control" #name="ngModel" name="name"
[(ngModel)]="order.name" required/>
<span *ngIf="submitted && name.invalid"
class="text-danger">
Please enter your name
</span>
</div>
<!--Address-->
<div class="form-group">
<label>Address</label>
<input class="form-control" #address="ngModel" name="address"
[(ngModel)]="order.address" required/>
<span *ngIf="submitted && address.invalid"
class="text-danger">
Please enter your Address
</span>
</div>
<!--City-->
<div class="form-group">
<label>City</label>
<input class="form-control" #city="ngModel" name="city"
[(ngModel)]="order.city" required/>
<span *ngIf="submitted && city.invalid"
class="text-danger">
Please enter your City
</span>
</div>
<!--State-->
<div class="form-group">
<label>State</label>
<input class="form-control" #state="ngModel" name="state"
[(ngModel)]="order.state" required/>
<span *ngIf="submitted && state.invalid" class="text-danger">
Please enter your State
</span>
</div>
<!--Zip-->
<div class="form-group">
<label>ZIP Postal Code</label>
<input class="form-control" #zip="ngModel" name="zip"
[(ngModel)]="order.zip" required/>
<span *ngIf="submitted && zip.invalid" class="text-danger">
Please enter your Zip Code
</span>
</div>
<!--Country-->
<div class="form-group">
<label>Country</label>
<input class="form-control" #country="ngModel" name="country"
[(ngModel)]="order.country" required/>
<span *ngIf="submitted && country.invalid" class="text-danger">
Please enter your Country
</span>
</div>
<!--Complete Order-->
<div class="text-center">
<!--Button Back-->
<button class]="btn btn primary m-1" routerLink="/cart">
Back
</button>
<!--Button Back-->
<button class="btn- btn-primary m-1" type="submit">
Complete Order
</button>
</div>
<!--Complete Order-->
</form>
<!--FORM-->
I had this error:
Uncaught (in promise) DOMException: Failed to execute 'setAttribute' on 'Element': '3' is not a valid attribute name.
And it turned out that I accidentally typed '3' at the bottom of the input field object. I just needed to be deleted.

Error in Sending form data to Django views through AJAX

I have a HTML form, which takes in input from the user. On clicking the submit button, form data needs to be sent to the views.py in a JSON format, through AJAX. I tried out something, but I am getting an error the JSON object must be str, not 'NoneType' . The JSON data is being loaded in the views.py through:
form = json.loads(request.POST.get('form'))
The data is returned in form of a dictionary called 'searchdata'.
The form:
<form method="POST" id="inputForm">
<div class="container" style="margin-bottom: 50px;width:100%">
<div class="container-fluid mt-3">
<div class="card" id="statform">
<div class="card-header">
<div class="card-title">
<div style="font-size: 25px">Filter</div>
</div>
</div>
<br>
<div class="card-body">
<div class="row">
<div class="col-xs-6">
<div class="col-xs-6">
<label name="start_date" class="control-label" style="width:35%">Start date</label>
<input type="date" id="start_date" style="color:black;width:100px" ></input>
</div>
</div>
<div class="col-xs-6">
<label name="end_date" class="control-label" style="width:35%">End Date(Default: Current Date)</label>
<input style="color:black;width:100px" id="end_date" type="date"></input>
</div>
</div>
<br>
<div class="row">
<div class="col-xs-6">
<label name="fruit_name" class="control-label" style="width:35%; padding-left:15px">Select a Fruit</label>
<select class="js-example-placeholder-single1 js-example-basic-multiple form-control" id="fruit_name" placeholder="Select" style="width:210px" multiple="multiple">
</select>
</div>
<div class="col-xs-6">
<label name="vendor_test" class="control-label" style="width:35%">Select Vendor_TEST</label>
<select class="js-example-placeholder-single2 js-example-basic-multiple form-control" style="width:210px" id="vendor_test" multiple="multiple">
</select>
</div>
</div>
<div class="row">
<div class="col-xs-6">
<label name="release_version" class="control-label" style="width:35%; padding-left:15px">Select Release version</label>
<select class="js-example-placeholder-single3 js-example-basic-multiple form-control" style="width:210px" id="release_version" multiple="multiple">
</select>
</div>
<div class="col-xs-6">
<label class="control-label" style="width:35%">Error Message</label>
<input type="text" placeholder="Type message here" style="width:210px">
</div>
</div>
<div class="row">
<div class="col-xs-6">
<label class="control-label" style="width:35%; padding-left:15px">Error Message List</label>
<select class="js-example-placeholder-single4 js-example-basic-multiple form-control" style="width:210px" id = "error_message" multiple="multiple">
</select>
</div>
</div>
<div class="text-center">
<button class="btn btn-md btn-default" type="submit" name="search" value="search" onclick="loadResults()">
<i class="fa fa-arrow-circle-right"></i> Submit
</button>
<button class="btn btn-md btn-default" type="reset" name="searchreset" value="reset">
<i class="fa fa-arrow-circle-right"></i> Reset
</button>
</div>
</div>
</div> <!--form-->
</div> <!-- row -->
</div> <!--container main-->
</form>
The AJAX call I have written:
$.ajax({
url : window.location.href,
type : 'POST',
cache : false,
data:{form:JSON.stringify(formdata)},
success:function(res){
if(typeof res.searchdata != 'undefined'){
self.$dispatch('searchdataevent',res.searchdata);
}
if(typeof res.message != 'undefined'){
self.message = res.message;
}
self.loading = false;
},
error : function(err){
self.message = 'Error communicating with server';
self.loading = false;
}
});
Where am I going wrong? Any help is appreciated.

Create Edit form with data from JSON url

so I have a pre-populated Bootstrap form with a Edit# button, I now want to edit the content. It gets data from the JSON url created from the Firebase database. It has User model.The functions are in the userprofile.component.ts . Please advise.
User Html page
<form class="needs-validation" novalidate >
<div class="row">
<div class="col-md-6 mb-3">
<label for="firstName">First name</label>
<input type="text" class="form-control" id="firstname" placeholder="first name"
value={{useritem.firstname}} required>
<div class="invalid-feedback">
Valid first name is required.
</div>
</div>
<div class="col-md-6 mb-3">
<label for="lastName">Last name</label>
<input type="text" class="form-control" id="lastname" placeholder="last name"
value={{useritem.lastname}} required>
<div class="invalid-feedback">
Valid last name is required.
</div>
</div>
</div>
<div class="btn-toolbar float-right">
<button class="btn btn-info mr-1" (click)="updateUser();">Update</button>
<button class="btn btn-dark " type="reset">Clear</button>
</div>
</form>
Firebase.service.ts
constructor(private httpClient: HttpClient) {}
public getuserprofile() : Observable<User[]>
{
return this.httpClient.get<User[]>(this.connectUrl);
}
updateuserprofile( user: User): Observable<User>
{
return this.httpClient.put<User>(this.connectUrl, user);
}
userprofile.component.ts
export class UserprofileComponent implements OnInit {
useritem: any = [];
constructor(private db: FirebaseService) { }
ngOnInit() {
this.getUser();
}
getUser() {
this.db.getuserprofile().subscribe(result =>
{
this.useritem = result;
console.log(result);
});
} }
Try to use for. ex Reactive Forms :
<form [formGroup]="form">
<div class="row">
<div class="col-md-6 mb-3">
<input formControlName="userName" placeholder="first name" >
<input formControlName="userLastName" placeholder="last name" >
</div></div>
<div class="btn-toolbar float-right">
<button class="btn btn-info mr-1" (click)="updateUser();">Update</button>
<button class="btn btn-dark " type="reset" (click)="reset()">Clear</button>
</div>
</form>
ts:
updateUser(){
this.newUser = {
userName: this.form.get('userName').value,
userLastName: this.form.get('userLastName').value
}
console.log(this.newUser) //here you can make PUT to firebase
}
reset(){
this.form.reset()
this.newUser = {}
}
https://stackblitz.com/edit/angular-1ixedr?file=src/app/app.component.ts
Hope it helps!

When sending the form, why is the value undefined?

I have a form
<form>
<div class="form-group">
<input class="form-control" ([ngModel])="login" placeholder="Login" required>
</div>
<div class="form-group">
<input type="password" class="form-control" ([ngModel])="password" placeholder="Password">
</div>
<div class="form-group">
<button (click)="logUpUser()" class="btn btn-primary">Sign Up</button>
</div>
</form>
and I want to send the value from HTML form to the typescript method
export class LogUpFormComponent implements OnInit {
login: string;
password: string;
constructor() { }
logUpUser() {
console.log(this.login);
}
}
but in the method logUpUser() I get the value of undefined. What am i doing wrong?
The correct HTML-Code has to look like this:
<form>
<div class="form-group">
<input class="form-control" [(ngModel)]="login" placeholder="Login" required>
</div>
<div class="form-group">
<input type="password" class="form-control" [(ngModel)]="password" placeholder="Password">
</div>
<div class="form-group">
<button (click)="logUpUser()" class="btn btn-primary">Sign Up</button>
</div>
</form>
And in your ts-File try this:
login: string = '';
password: string = '';