Just for experimenting with dynamic contact form validation using AngularJS
A Pen by Stan Williams on CodePen.
Just for experimenting with dynamic contact form validation using AngularJS
A Pen by Stan Williams on CodePen.
<div class="container" ng-app="ContactForm"> | |
<h1>AngularJS Contact Form</h1> | |
<form name="cf" ng-controller="cfController as cfCtrl" ng-submit="submitForm(cf.$valid)" novalidate> | |
<div class="form-group"> | |
<label for="name">Name</label> | |
<input id="name" type="text" name="name" ng-model="name" required> | |
</div> | |
<div class="form-group"> | |
<label for="email">Email (optional)</label> | |
<input id="email" type="email" name="email"> | |
</div>to | |
<div class="form-group"> | |
<label for="msg">Message</label> | |
<textarea id="msg" name="message" rows="4" ng-model="msg" required></textarea> | |
</div> | |
<input type="submit" value="Send" ng-disabled="cf.$invalid"/> | |
</form> | |
</div> |
var app = angular.module('ContactForm',[]); | |
app.controller("cfController",function($scope){ | |
$scope.submitForm = function(isValid) { | |
this.formInput = { | |
name: $("input[name='name']").val(), | |
email: $("input[name='email']").val(), | |
message: $("textarea[name='message']").val() | |
}; | |
if (isValid) { | |
console.log('Message sent successfully'); | |
console.log(this.formInput); | |
} else { | |
console.log('Failed to send message') | |
} | |
}; | |
}); |
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script> | |
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.min.js"></script> |
body, input, textarea { | |
font-family: Open Sans, Helvetica, sans-serif; | |
font-size: 16px; | |
} | |
body { | |
background: #ddd; | |
color: #333; | |
} | |
label { | |
display: block; | |
font-weight: 700; | |
margin: 0 0 8px 0; | |
min-width: 50px; | |
} | |
input, textarea { | |
border: 1px solid #ccc; | |
padding: 4px 0; | |
width: 100%; | |
-webkit-appearance: none; | |
} | |
input[type=submit] { | |
background: #4a4; | |
border: 0; | |
color: #fff; | |
padding: 8px 16px; | |
transition: background 0.2s; | |
} | |
input[type=submit]:not(:disabled):hover { | |
background: #6c6; | |
} | |
input[type=submit]:not(:disabled):active { | |
background: #383; | |
} | |
input[disabled] { | |
opacity: 0.5; | |
} | |
.container { | |
background: #fff; | |
box-shadow: 0 2px 4px #888; | |
margin: auto; | |
padding: 16px; | |
max-width: 600px; | |
} | |
.form-group { | |
margin-bottom: 16px; | |
} | |
input.ng-invalid.ng-dirty, | |
textarea.ng-invalid.ng-dirty{ | |
border-color: red; | |
box-shadow: 0 0 4px red; | |
} |