AngularJS Contact Form - javascript

I'm pretty new to AngularJS and trying to build a contact form. I did some research to validate with angular, this works fine. However sending the input to my email account is still a mystery.
HTML Snippet
<form name="contactForm" ng-submit="submitForm(contactForm.$valid)" novalidate> <!-- novalidate prevents HTML5 validation since we will be validating ourselves -->
<!-- NAME -->
<div class="form-group" ng-class="{ 'has-error' : contactForm.name.$invalid && !contactForm.name.$pristine }">
<input type="text" name="name" class="form-control" ng-model="formData.name" placeholder="Volledige naam" ng-minlength="3" required>
<p ng-show="contactForm.name.$error.minlength" class="help-block">Je naam lijkt iets te kort, vul ook je achternaam in!</p>
</div>
<!-- EMAIL -->
<div class="form-group" ng-class="{ 'has-error' : contactForm.email.$invalid && !contactForm.email.$pristine }">
<input type="email" name="email" class="form-control" ng-model="formData.email" placeholder="Email adres" required>
<p ng-show="contactForm.email.$invalid && !contactForm.email.$pristine" class="help-block">Voer een geldig email adres in</p>
</div>
<!-- TEL -->
<div class="form-group" ng-class="{ 'has-error' : contactForm.tel.$invalid && !contactForm.tel.$pristine }">
<input type="tel" name="tel" class="form-control" ng-model="formData.tel" placeholder="Telefoonnummer" min-length="10" required>
<p ng-show="contactForm.tel.$error.minlength" class="help-block">Je telefoonnummer lijkt iets te kort, misschien mis je iets als "+31" of "043"</p>
</div>
<!-- TEXT -->
<div class="form-group" ng-class="{ 'has-error' : contactForm.text.$invalid && !contactForm.text.$pristine }">
<textarea name="text" class="form-control" ng-model="formData.text" placeholder="Formuleer uw situatie kort. Geef ook aan op welke dagen u beschikbaar bent of gebeld wenst te worden." ng-minlength="10" required></textarea>
<p ng-show="contactForm.text.$error.minlength" class="help-block">Vertel ons iets meer...</p>
</div>
<!-- SUBMIT BUTTON -->
<input type="submit" ng-submit="processForm()" ng-disabled="contactForm.$invalid" value="Maak afspraak">
<!-- <pre>
{{formData}}
</pre> -->
</form>
Controller
.controller('MainCtrl', function($scope, $http) {
this.features = keys;
$scope.submitForm = function(isValid) {
if (isValid) {
$scope.formData = {};
$scope.processForm = function() {
$http({
method : 'POST',
url : 'process.php',
data : $.param($scope.formData),
headers : { 'Content-Type': 'application/x-www-form-urlencoded' }
});
};
}
};
})
The process.php file is still empty since I'm not quite sure what to put here.

Regarding your form submission setup, you cannot put the ng-submit on any input[type="submit"] elements, instead you put ng-click. Also, according to the angular docs, when you have a ng-submit on the form, and an ng-click on any input[type="submit"] elements, the ng-click handlers will get called first, THEN the ng-submit handler will get called (your controller is set up for the opposite order).
But in your case, two submit handlers is unneccessary, as you can do all your validation with angular directives, and just use an ng-click. Theres an example plunker here.
HTML:
<div ng-controller="MainCtrl">
<form name="contactForm" novalidate>
<!-- NAME -->
<div ng-class="{'form-error':contactForm.name.$dirty && contactForm.name.$invalid, 'form-group':true}">
<input type="text" name="name" ng-model="formData.name" placeholder="Volledige naam" ng-minlength="3" required="" />
<div ng-messages="contactForm.name.$error" ng-show="contactForm.name.$dirty" >
<div ng-message="minlength">Name too short</div>
<div ng-message="required">Required Name</div>
</div>
</div>
<!-- EMAIL -->
<div ng-class="{'form-error':contactForm.email.$dirty && contactForm.email.$invalid, 'form-group':true}">
<input type="email" name="email" ng-model="formData.email" placeholder="Email adres" required />
<div ng-messages="contactForm.email.$error" ng-show="contactForm.email.$dirty">
<div ng-message="email">Invalid Email</div>
<div ng-message="required">Required Email</div>
</div>
</div>
<!-- TEL -->
<div ng-class="{'form-error':contactForm.tel.$dirty && contactForm.tel.$invalid, 'form-group':true}">
<input type="text" name="tel" ng-pattern=/\d{3}-\d{3}-\d{4}/ ng-model="formData.tel" placeholder="Telefoonnummer" required />
<div ng-messages="contactForm.tel.$error" ng-show="contactForm.tel.$dirty">
<div ng-message="pattern">Valid form: XXX-XXX-XXXX</div>
<div ng-message="required">Required Phone</div>
</div>
</div>
<!-- SUBMIT BUTTON -->
<input type="submit" ng-click="processForm()" ng-disabled="contactForm.$invalid" value="Maak afspraak" />
</form>
</div>
JavaScript:
.controller('MainCtrl', function($scope, $http) {
$scope.formData = {};
$scope.processForm = function() {
alert('valid form!')
$http({
method : 'POST',
url : 'process.php',
data : $scope.formData,
headers : { 'Content-Type': 'application/x-www-form-urlencoded' }
});
};
});
Regarding the submission to your email, the $http service will post your data using the http protocol, so you cannot send it directly to you email, as email does not use the HTTP protocol for communication. You Could send the post data to your server, and have the server send the email (e.g. if you use Node you can use nodemailer package to send the email).

Just copy below code in your angularJs Project it will work fine
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular.min.js"></script>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<div class="container">
<div class="row" style="margin-bottom:15px;">
<div class="col-md-12">
<div class="col-md-offset-1 col-md-6" id="box">
<h2 class="colr">Contact Us!</h2>
<hr>
<form class="form-horizontal" name="contactForm" ng-submit="submitContactForm(ContactDetails)" novalidate>
<fieldset>
<!-- Form Name -->
<!-- Text input-->
<div class="form-group">
<div class="col-md-12" ng-class="{ 'has-error' : contactForm.first_name.$invalid && !contactForm.first_name.$pristine }">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
<input name="first_name" placeholder="Name" ng-model="ContactDetails.FirstName" class="form-control" type="text" required>
</div>
<span ng-show="contactForm.first_name.$invalid && !contactForm.first_name.$pristine" class="help-block">Username is required.</span>
</div>
</div>
<!-- Text input-->
<div class="form-group">
<div class="col-md-12" ng-class="{ 'has-error' : contactForm.email.$invalid && !contactForm.email.$pristine }">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-envelope"></i></span>
<input name="email" placeholder="E-Mail Address" ng-model="ContactDetails.Email" class="form-control" type="text" ng-pattern="/^[_a-z0-9]+(\.[_a-z0-9]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/">
</div>
<span ng-show="contactForm.email.$invalid && !contactForm.email.$pristine" class="help-block"> Enter a valid email.</span>
</div>
</div>
<!-- Text input-->
<div class="form-group" ng-class="{ 'has-error' : contactForm.phone.$invalid && !contactForm.phone.$pristine }">
<div class="col-md-12">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-earphone"></i></span>
<input type="text" class="form-control" ng-model="ContactDetails.PhoneNumber" name="phone" ng-maxlength="10" ng-minlength="10" placeholder="9845640899" required>
</div>
<span ng-show="contactForm.phone.$invalid && !contactForm.phone.$pristine">Phone Number is required.</span>
</div>
</div>
<div class="form-group" ng-class="{ 'has-error' : contactForm.subject.$invalid && !contactForm.subject.$pristine }">
<div class="col-md-12">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-bookmark"></i></span>
<input name="subject" ng-model="ContactDetails.Subject" placeholder="Enter Subject" class="form-control" type="text" required>
</div>
<span ng-show="contactForm.subject.$invalid && !contactForm.subject.$pristine" class="help-block">Subject is required.</span>
</div>
</div>
<!-- Text input-->
<div class="form-group" ng-class="{ 'has-error' : contactForm.comment.$invalid && !contactForm.comment.$pristine }">
<div class="col-md-12 inputGroupContainer">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-pencil"></i></span>
<textarea class="form-control" ng-model="ContactDetails.Comment" rows="6" name="comment" placeholder="Message" ng-maxlength="255" ng-minlength="10" required></textarea>
</div>
<span ng-show="contactForm.comment.$invalid && !contactForm.comment.$pristine" class="help-block"> Enter a Message.</span>
</div>
</div>
<div class="form-group">
<div class="col-md-12">
<button type="submit" class="btn btn-warning pull-right" ng-disabled="contactForm.$invalid">Send<span class="glyphicon glyphicon-send"></span>
</button>
</div>
</div>
</fieldset>
</form>
</div>
</div>
</div>
</div>

Related

Combine two field in email field

laravel
I'm struggling to put the result of two concatme fields in another field input.
I would like to put the results of response in the email field input.
The thing I would like to achieve is to make it easier for the user to log in to the system without putting the whole email address john#box.domain.com.
here is the code so far.
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2">
#include('auth/banner')
<div class="panel panel-default panel-shaded">
<div class="panel-body">
#action('login_form.before')
<form class="form-horizontal margin-top" method="POST" action="{{ route('login') }}">
{{ csrf_field() }}
<div class="form-group{{ $errors->has('email') ? ' has-error' : '' }}">
<label for="email" class="col-md-4 control-label">{{ __('Email Address') }}</label>
<div class="col-md-6">
<!-- SCRIPT -->
<script type="text/javascript">
function concatme()
{
var num1 = document.getElementById("num1").value;
var num2 = document.getElementById("num2").value;
document.getElementById("response").innerText = num1 + '' +num2;
}
</script>
<!-- FIN SCRIPT -->
<!---- INICIO---->
<input type="text" name="num1" class="form-control" id="num1" placeholder="USER">
<input type="text" name="num2" class="form-control" id="num2" value="#box.domain.com" placeholder="Number 2">
<!---FIN-->
<!-- RESUTLADO PREVIEW -->
<p id="response"></p>
<!-- RESULDADO PREVIEW -->
<input id="email" type="email" class="form-control" name="email" value="{{ old('email') }}" required autofocus>
#if ($errors->has('email'))
<span class="help-block">
<strong>{{ $errors->first('email') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group{{ $errors->has('password') ? ' has-error' : '' }}">
<label for="password" class="col-md-4 control-label">{{ __('Password') }}</label>
<div class="col-md-6">
<input id="password" type="password" class="form-control" name="password" required>
#if ($errors->has('password'))
<span class="help-block">
<strong>{{ $errors->first('password') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group">
<div class="col-md-6 col-md-offset-4">
<label class="checkbox">
<input type="checkbox" name="remember" {{ old('remember') ? 'checked' : '' }}> {{ __('Remember Me') }}
</label>
</div>
</div>
<div class="form-group">
<div class="col-md-8 col-md-offset-4">
<button type="submit" onclick="concatme()" class="btn btn-primary">
{{ __('Login') }}
</button>
#if (Eventy::filter('auth.password_reset_available', true))
<a class="btn btn-link" href="{{ route('password.request') }}">
{{ __('Forgot Your Password?') }}
</a>
#endif
</div>
</div>
</form>
<p>Hola</p>
#action('login_form.after')
</div>
</div>
</div>
</div>
</div>
#endsection
I think its working but you are not able to see it because you have use form and called javascript function on submit button.
What happens is its sending request to given route and refreshing page thats make paragraph tag to empty again. Remove type submit from submit button and then confirm if its working or not.

how to show validation message on button click?

could you please tell me how to show validation message on button click ? here is my code
https://stackblitz.com/edit/angular-ugdbvg?file=src/app/app.component.html
I want to show required error message when user press submit button.
<form novalidate [formGroup]="searchForm" class="calform">
<section class="col-sm-6 bg-white pl-20 pr-20">
<div class="form-group col-sm-4 pl-0 error">
<label class="field-title mb-5">name<span class="color-red fontWt"> *</span></label>
<input type="text" placeholder="Enter name" formControlName="name">
<p class="message" [hidden]="searchForm.get('name')">Required</p>
</div>
<div class="form-group col-sm-4 pl-0 error">
<label class="field-title mb-5">last name <span class="color-red fontWt"> *</span></label>
<input type="text" placeholder="Enter last name" formControlName="lastName">
<p class="message" [hidden]="searchForm.get('lastName')">Required</p>
</div>
<button (click)="submitHandler()">submit</button>
</section>
</form>
js
this.searchForm = this.fb.group({
name: ['', Validators.required],
lastName: ['', Validators.required]
});
Add the following line to check:
<span class="error" *ngIf="!!searchForm.controls.name.errors.required && (!!searchForm.controls.name.dirty || !!searchForm.controls.name.touched)">
Name is required.
</span>
<span class="error" *ngIf="!!searchForm.controls.lastName.errors.required && (!!searchForm.controls.lastName.dirty || !!searchForm.controls.name.touched)">
lastName is required.
</span>
in your ts file:
submitHandler() {
if(this.searchForm.valid) {
// Logic
}
}
https://stackblitz.com/edit/angular-utvw23
You need to use *ngIf. Updated Stackblitz code . https://stackblitz.com/edit/angular-fzyrji
Try like this:
Use [hidden] or *ngIf
DEMO
<div class="form-group col-sm-4 pl-0 error">
<label class="field-title mb-5">name<span class="color-red fontWt"> *</span></label> {{show}}
<input type="text" placeholder="Enter name" formControlName="name"> {{searchForm.get('name').invalid}}
<p class="message" [hidden]="!(show && searchForm.get('name').invalid)">Required</p>
</div>
<div class="form-group col-sm-4 pl-0 error">
<label class="field-title mb-5">last name <span class="color-red fontWt"> *</span></label>
<input type="text" placeholder="Enter last name" formControlName="lastName">
<p class="message" [hidden]="!(show && searchForm.get('lastName').invalid)">Required</p>
</div>
<button (click)="show = true ; submitHandler();">submit</button>
</section>
</form>

Angular JS textarea validation with required & showing error message

I have a Angular JS code where i want to implement validation and focus on the field back if textarea is empty.
<form ng-submit="addComment()" role="form" name="blogForm" novalidate>
<div class="form-group" ng-class="{ 'has-error' : blogForm.blogComment.$invalid && replySubmitted }">
<textarea ng-model="blogComment" name="blogComment" class="form-control" rows="3" ng-required="true" required></textarea>
</div>
<div style="color:#a94442;" ng-show="blogForm.blogComment.$invalid && replySubmitted">
<span ng-show="blogForm.blogComment.$error.required">Comment Text required.</span>
</div>
<button type="submit" ng-click="replySubmitted = true" class="btn btn-primary blog-bubmit-button">Submit</button>
</form>
For some reasons the above code is just inserting empty data and field is focused Invalid.
Any Suggestions may help me.
Thanku
you have define ng-app to process it as angular block.
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app=''>
<form ng-submit="addComment()" role="form" name="blogForm" novalidate>
<div class="form-group" ng-class="{ 'has-error' : blogForm.blogComment.$invalid && replySubmitted }">
<textarea ng-model="blogComment" name="blogComment" class="form-control" rows="3" ng-required="true" required></textarea>
</div>
<div style="color:#a94442;" ng-show="blogForm.blogComment.$invalid && replySubmitted">
<span ng-show="blogForm.blogComment.$error.required">Comment Text required.</span>
</div>
<button type="submit" ng-click="replySubmitted = true" class="btn btn-primary blog-bubmit-button">Submit</button>
</form>
</div>

Angular Signup page using ui-router not able to access the html page

I have an angular sign-up page. This is the directory structure of my project:
singUpPage-Angular
bin
bower_components
model
mongodbApp.js
node_modules
**partials
fail.html
main.html
success.html**
public
images
**javascripts
signUp.js**
stylesheets
routes
index.js
users.js
**views
index.ejs**
app.js
package.json
All my html is in partials folder
The javascript controller code is in signup.js
The main html is in views index.ejs.
I have tried to acces the html using the ui router and the code is not working. I am not sure if itis an error with the path or if there is a prolem with ui-router code.
The router does not take me to the page:
When I run the code: on the address bar I get: http://localhost:3000/#/partials/main.html: but nothing from the main page get displayed. I dont seem to get an errors either.
index.ejs
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel='stylesheet' href='/stylesheets/style.css' />
<script src="/angular/angular.js"></script>
<script src="/ui-router/release/angular-ui-router.min.js"></script>
<script src="/javascripts/signUp.js"></script>
</head>
<body ng-controller="myCtrl">
<div ui-view></div>
</body>
</html>
signUp.js
angular.module("myApp",['ui.router'])
.config(function($stateProvider, $urlRouterProvider){
$urlRouterProvider.otherwise('partials/main.html');
$stateProvider
.state('success', {
url: "/success",
templateUrl:'partials/success.html'
})
.state('fail', {
url: '/fail',
templateUrl:'partials/fail.html'
})
})
.controller("myCtrl", function($scope, SignUp,$state){
$scope.clearPerson = function(){
$scope.first = "";
$scope.last = "";
$scope.email = "";
$scope.password = "";
$scope.confirm = "";
$scope.dob = "";
}
$scope.addPerson = function(){
/* console.log($scope.first);
console.log($scope.last);
console.log($scope.email);
console.log($scope.password);
console.log($scope.confirm);
console.log($scope.dob);*/
$scope.person = {
firstName: $scope.first,
lastName: $scope.last,
email: $scope.email,
password:$scope.password,
dateOfBirth: $scope.dob
}
console.log($scope.person);
SignUp.add($scope.person).success(function(res){
$state.go("success");
console.log(res);
}).error(function(res){
$state.go("fail");
console.log("error");
})
}
})
.factory("SignUp", function($http){
return{
add: function(person){
return $http.post('/signup',person);
}
}
})
main.html
<h1>Sign up Page</h1>
<div class="new-container">
<div class="container">
<h3>Create an ID</h3>
<form class="form-horizontal" name="signup" novalidate ng-submit="addPerson()">
<div class="form-group">
<h4>Name</h4>
<label class="col-sm-2 label-control align-text" >First Name</label>
<div class="col-sm-4 text-margin" >
<input name="first" ng-maxlength=50 ng-model="first" type="text" class="form-control" required>
<div class="error"
ng-show="signup.first.$dirty && signup.first.$invalid">
<small class="error"
ng-show="signup.first.$error.required">
Your name is required.
</small>
<small class="error"
ng-show="signup.first.$error.maxlength">
Your name cannot be longer than 50 characters
</small>
</div>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 label-control align-text" >Last Name</label>
<div class="col-sm-4 text-margin">
<input name="last" ng-maxlength=50 ng-model="last" type="text" class="form-control" placeholder="optional">
<div class="error"
ng-show="signup.last.$dirty && signup.last.$invalid">
<small class="error"
ng-show="signup.last.$error.maxlength">
Your name cannot be longer than 50 characters
</small>
</div>
</div>
</div>
<div class="form-group">
<h4>ID and Password</h4>
<label class="col-sm-2 align-text label-control">Username</label>
<div class="col-sm-4 text-margin">
<input name="email" ng-maxlength=56 ng-model="email" type="email" class="form-control" placeholder="Email" required>
<div class="error"
ng-show="signup.email.$dirty && signup.email.$invalid">
<small class="error"
ng-show="signup.email.$error.required">
Your email is required.
</small>
<small class="error"
ng-show="signup.email.$error.maxlength">
Your name cannot be longer than 56 characters
</small>
</div>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 label-control align-text">Password</label>
<div class="col-sm-4 text-margin">
<input name="password" ng-minlength=6 ng-model="password" type="password" class="form-control al" placeholder="Password" required>
<div class="error"
ng-show="signup.password.$dirty && signup.password.$invalid">
<small class="error"
ng-show="signup.password.$error.required">
Your password is required.
</small>
<small class="error"
ng-show="signup.password.$error.minlength">
Your name cannot be atleast 6 characters long.
</small>
</div>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 label-control align-text">Confirm Password</label>
<div class="col-sm-4 text-margin">
<input name="confirm" compare-to="password" ng-model="confirm" type="password" class="form-control" placeholder="Password" required>
<div class="error"
ng-show="signup.confirm.$dirty && signup.confirm.$invalid">
<small class="error"
ng-show="signup.confirm.$error.required">
Password confirmation is required.
</small>
<small class="error"
ng-show="signup.confirm.$error.errorCompareTo">
Your passwords do not match.
</small>
</div>
</div>
</div>
<div class="form-group">
<h4>Date of Birth</h4>
<label class="col-sm-2 label-control align-text">Birthday</label>
<div class="col-sm-4 text-margin">
<input ng-model="dob" type="date" class="form-control" placeholder="MM/DD/YYYY" required>
</div>
</div>
<div class="form-group" >
<div class="col-sm-offset-2 col-sm-10 float-right" >
<button type="submit" class="btn signUp" >Sign Up</button>
<button type="submit" class="btn btn-default" ng-click="clearPerson()">Clear</button>
</div>
</div>
</form>
</div>
</div>
fail.html
<h1>fail</h1>
success.html
<h1>success</h1>
Do this
$urlRouterProvider.otherwise('/');
In State
$stateProvider
.state('main', {
url: "/",
templateUrl:'partials/main.html'
})
This will open your signUpPage

Angular ng-messages: how to check password confirmation?

THE SITUATION:
I am using ng-messages directive for instant validation in my angular app. Everything is working fine except one thing: i need to validate the field 'password confirmation' and don't know how to do.
THE CODE:
<form name="autentication_form" novalidate="" ng-submit="submit_register()">
<label class="item item-input">
<span class="input-label">Email</span>
<input type="text" name="email" ng-model="registerData.email" required>
<div class="form-errors" ng-messages="autentication_form.email.$error" role="alert" ng-if='autentication_form.email.$dirty'>
<div class="form-error" ng-message="required">You did not enter the email</div>
</div>
</label>
<label class="item item-input">
<span class="input-label">Password</span>
<input type="password" name="password" ng-model="registerData.password" required>
<div class="form-errors" ng-messages="autentication_form.password.$error" role="alert" ng-if='autentication_form.password.$dirty'>
<div class="form-error" ng-message="required">Please enter the password</div>
</div>
</label>
<label class="item item-input">
<span class="input-label">Password confirmation</span>
<input type="password" name="password_confirmation" ng-model="registerData.password_confirmation" required>
<div class="form-errors" ng-messages="autentication_form.password_confirmation.$error" role="alert" ng-if='autentication_form.password_confirmation.$dirty'>
<div class="form-error" ng-message="required">Password confirmation required</div>
</div>
</label>
</form>
THE QUESTION:
How can i check that the password confirmation match using ng-messages?
The easiest approach is to use a pattern. Works fine for me!
<input type="password" name="new_password1" ng-model="new_password1">
<input type="password" name="new_password2" ng-pattern="\b{{new_password1}}\b" ng-model="new_password2">
<div ng-messages="passwordForm.new_password2.$error">
<div ng-message="pattern">Not equal!!!</div>
</div>
The best approach is to use a directive. The major point of problem here is that both password and password confirmation inputs need to be watched.
Here's the solution that could help
angular.module('app', ['ngMessages'])
.controller('ctrl', function($scope) {
$scope.registerData = {};
})
.directive('confirmPwd', function($interpolate, $parse) {
return {
require: 'ngModel',
link: function(scope, elem, attr, ngModelCtrl) {
var pwdToMatch = $parse(attr.confirmPwd);
var pwdFn = $interpolate(attr.confirmPwd)(scope);
scope.$watch(pwdFn, function(newVal) {
ngModelCtrl.$setValidity('password', ngModelCtrl.$viewValue == newVal);
})
ngModelCtrl.$validators.password = function(modelValue, viewValue) {
var value = modelValue || viewValue;
return value == pwdToMatch(scope);
};
}
}
});
<html ng-app="app">
<head>
<script data-require="angular.js#~1.4.3" data-semver="1.4.3" src="https://code.angularjs.org/1.4.3/angular.js"></script>
<script data-require="angular-messages#1.4.3" data-semver="1.4.3" src="https://code.angularjs.org/1.4.3/angular-messages.js"></script>
<script src="https://code.angularjs.org/1.3.15/angular.js"></script>
<script src="script.js"></script>
</head>
<body ng-controller="ctrl">
<form name="autentication_form" novalidate="" ng-submit="submit_register()">
<label class="item item-input">
<span class="input-label">Email</span>
<input type="text" name="email" ng-model="registerData.email" required="" />
<div class="form-errors" ng-messages="autentication_form.email.$error" ng-if='autentication_form.email.$touched'>
<span class="form-error" ng-message="required">You did not enter the email</span>
</div>
</label>
<label class="item item-input">
<span class="input-label">Password</span>
<input type="password" name="password" ng-model="registerData.password" required />
<div class="form-errors" ng-messages="autentication_form.password.$error" ng-if='autentication_form.password.$touched'>
<span class="form-error" ng-message="required">Please enter the password</span>
</div>
</label>
<label class="item item-input">
<span class="input-label">Password confirmation</span>
<input type="password" name="password_confirmation" ng-model="registerData.password_confirmation" required="" confirm-pwd="registerData.password" />
<div class="form-errors" ng-messages="autentication_form.password_confirmation.$error" ng-if='autentication_form.password_confirmation.$touched'>
<span class="form-error" ng-message="required">Password confirmation required</span>
<span class="form-error" ng-message="password">Password different</span>
</div>
</label>
</form>
</body>
</html>
When developing, you can face the fact that you need to create your own checks, which will affect the validity of the form. If these checks are simple, such as a comparison of the two values, it is better to use a general guideline, than write your own checks for each situation. Look at use-form-error directive.
Live example on jsfiddle.
angular.module('ExampleApp', ['use', 'ngMessages'])
.controller('ExampleController', function($scope) {
});
.errors {
color: maroon
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular-messages.min.js"></script>
<script src="https://cdn.rawgit.com/Stepan-Kasyanenko/use-form-error/master/src/use-form-error.js"></script>
<div ng-app="ExampleApp">
<div ng-controller="ExampleController">
<form name="ExampleForm">
<label>Password</label>
<input ng-model="password" required />
<br>
<label>Confirm password</label>
<input ng-model="confirmPassword" name="confirmPassword" use-form-error="isNotSame" use-error-expression="password && confirmPassword && password!=confirmPassword" required />
<div ng-show="ExampleForm.$error.isNotSame" class="errors">Passwords Do Not Match!</div>
<div ng-messages="ExampleForm.confirmPassword.$error" class="errors">
<div ng-message="isNotSame">
Passwords Do Not Match (from ng-message)!
</div>
</div>
</form>
</div>
</div>
Here's what I did (using ng-pattern):
<md-input-container class="md-block">
<label>New Password</label>
<input ng-model="user.password" name="password" type="password" required ng-pattern="'.{8,}'" />
<div ng-messages="form.password.$error">
<div ng-message="required">Password required.</div>
<div ng-message="pattern">Password must be at least 8 characters.</div>
</div>
</md-input-container>
<md-input-container class="md-block">
<label>Confirm Password</label>
<input ng-model="user.confirmPassword" name="confirmPassword" type="password" ng-pattern="user.password|escapeRegex" required />
<div ng-messages="form.confirmPassword.$error">
<div ng-message="required">Password confirmation required.</div>
<div ng-message="pattern">Passwords do not match.</div>
</div>
</md-input-container>
And the following filter converts the ng-pattern regex to a literal:
module.filter('escapeRegex', function(){
return function(str){
return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
}
});
ngMessage works by adding $error.message_field_name to the DOM field name in the form object (within the scope of course). So if your DOM form name is autentication_form and the DOM field name is password_confirmation, you need to set $scope.autentication_form.password_confirmation.$error.nomatch (or whatever ngMessage name you want) to true to display the "Doesn't match" error.
Markup:
<input type="password" name="password_confirmation" ng-model="registerData.password_confirmation" required />
<div ng-messages="autentication_form.password_confirmation.$error">
<div ng-message="required">Please repeat your password.</div>
<div ng-message="nomatch">Doesn't match.</div>
</div>
</div>
Code, nothing special, just watching both passwords:
$scope.$watch("registerData.password + registerData.password_confirmation", function () {
$scope.autentication_form.password_confirmation.$error.nomatch = $scope.registerData.password !== $scope.registerData.password_confirmation;
});
i did using only ionic(html) validations.
New Password
New Password is required
<label class="item item-input inputRadius">
<span class="input-label">Confirm Password</span>
<input type="password" placeholder="Confirm Password" ng-model="passwordUpdateInfo.confirmPassword" name="confirmPassword" required>
</label>
<div ng-show="passwordUpdateForm.$submitted || passwordUpdateForm.confirmPassword.$touched">
<div ng-show="passwordUpdateForm.confirmPassword.$error.required" class="errorMessage">Confirm Password is required</div>
</div>
<div ng-show="passwordUpdateInfo.confirmPassword.length > 0 && passwordUpdateInfo.confirmPassword != passwordUpdateInfo.newPassword">
Password not match..(amar from india)
</div>
<button class="button button-positive button-block" ng-disabled="passwordUpdateInfo.confirmPassword.length > 0 && passwordUpdateInfo.confirmPassword != passwordUpdateInfo.newPassword">Update</button>

Categories