I gave a validation to test field by giving required to it as
<div class="form-group">
<label for="inputEmail" class="col-lg-4 col-lg-offset-1 control-label">Email address</label>
<div class="col-lg-4">
<input class="form-control" ng-model="$root.customerDetails.eMail" placeholder="Enter customer email" type="email" required focus value = "{{emailId}}">
</div>
</div>
and then i'm clicking submit button,but the validation is not working. I'm able to proceed to next page with out email.
Is there any other way to do the validation.
Can someone help me
Thanks
It should be like:
The validation not stop the submission automatically. In your submit function you need to check if the forum is valid.
Like this:
angular.module('app', []).
controller('ctrl', function($scope) {
$scope.submit = function() {
console.log('submitted');
}
});
.validation {
font-size: 80%;
color: red;
}
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
<form name="myForm">
<input type="text" name="txt" ng-model="txt" required /><br />
<!--<div class="validation" ng-show="myForm.$submitted && myForm.txt.$invalid">Please fill out the field</div>-->
<button ng-click="myForm.$valid && submit()">Submit</button><br />
Form is valid: {{myForm.$valid}}
</form>
</div>
Related
In our contact form, I'm trying to only allow submissions from email addresses from the United States, since we can only do business in that one country. How can I trigger the default error message when a form submit attempt is made, so that "invalid" message appears the same way it appears for the first name and last name fields?
In the code below, for the sake of example, I'm allowing only 'com', 'edu', 'gov', 'net', 'org'. The goal is to trigger a message whenever an email address other than those above is entered into the email field.
$(document).ready(function() {
$(function() {
$("#testform").submit(function() {
str = $('input[name=emailAddress]').val();
str = str.split('#').slice(0);
str = str[1].split('.').slice(0);
var allowedDomains = ['com', 'edu', 'gov', 'net', 'org'];
alert("str = " + str[1]);
if ($.inArray(str[1], allowedDomains) !== -1) {
alert(str + ' is allowed');
} else {
alert('not allowed');
event.preventDefault();
event.stopPropagation();
$('#emailAddress').addClass('invalid');
}
});
});
});
<link href="https://getbootstrap.com/docs/4.0/dist/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://getbootstrap.com/docs/4.0/assets/js/vendor/holder.min.js"></script>
<script src="https://getbootstrap.com/docs/4.0/dist/js/bootstrap.min.js"></script>
<script src="https://getbootstrap.com/docs/4.0/assets/js/vendor/popper.min.js"></script>
<div class="container">
<form action="" method="post" target="" class="needs-validation" role="form" id="testform">
<fieldset>
<div class="form-group">
<label for="firstName" class="col-form-label">Customer first name:
<input type="text" class="form-control" name="firstName" id="firstName" required aria-required="true">
</label>
</div>
<div class="form-group">
<label for="lastName" class="col-form-label">Customer last name:
<input type="text" class="form-control" name="lastName" id="lastName" required aria-required="true">
</label>
</div>
<div class="form-group">
<label for="emailAddress" class="col-form-label">Customer email address:
<input type="email" class="form-control" name="emailAddress" id="emailAddress" required placeholder="Enter valid email" aria-required="true">
</label>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</fieldset>
</form>
</div>
I am intend to use javascript to submit the form. Before I want to submit the form, I need to validate my form.
The following is my code :
alert("OP Please edit me to add the validation script code, cdn link or something. Add code that triggers the validation.");
function validateForm1() {
$("#addMapForm").validate();
$('#addMapForm').valid();
console.log($('#addMapForm').valid());
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/jquery.validate.min.js"></script>
<form enctype="multipart/form-data" action="/Admin/AddMap" method="post" id="addMapForm">
<div>
<br />
<br />
<div class="col-md-12">
<div class="form-group">
<label>Location Name *</label>
<input class="form-control" required />
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label>Unit/ Floor Number</label>
<input class="form-control" />
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label>Address*</label>
<textarea class="form-control" style="height:100px" required></textarea>
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label>Town/ City *</label>
<input class="form-control" required />
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label>Zip Code*</label>
<input class="form-control" required/>
</div>
</div>
</div>
</form>
You are missing names on the inputs. A form will only submit named controls and validation plugin won't validate anything without a name
The required fields work fine once you add them
$("#addMapForm").validate();
$("#addMapForm").valid();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/jquery.validate.min.js"></script>
<form enctype="multipart/form-data" action="/Admin/AddMap" method="post" id="addMapForm">
<div>
<br />
<br />
<div class="col-md-12">
<div class="form-group">
<label>Location Name *</label>
<input name="location" class="form-control" required />
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label>Unit/ Floor Number</label>
<input name="unit" class="form-control" />
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label>Address*</label>
<textarea name="address" class="form-control" style="height:100px" required></textarea>
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label>Town/ City *</label>
<input name="city" class="form-control" required />
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label>Zip Code*</label>
<input name="zip" class="form-control" required/>
</div>
</div>
</div>
<button>Submit</button>
</form>
I assume you are using this: https://jqueryvalidation.org/validate/
Have you implemented the rules of validation for other elements?
rules (default: rules are read from markup (classes, attributes, data))
So either you have those defined in HTML or you need to define them inside validate function called before you called .valid().
Here is an examle:
$("#myform").validate({
rules: {
// simple rule, converted to {required:true}
name: "required",
// compound rule
email: {
required: true,
email: true
}
}
});
In short for more precise help we need all the relevant code or fiddle, plunker a demo showing the example of the problem you are facing.
Try this solution.
$('.form-control').each(function() {
$(this).validate();
$(this).valid();
}
I tried to use the following js to validate all my form, however i know the following code is not the best answer, it only able to show the error message on the first input element.
I am welcome to anyone to post better answer than this.
function validateForm() {
var result = true;
$("#addMapForm").each(function () {
$(this).find(':input').each(function () {
if ($(this).valid() == false) {
result = false;
return;
}
});
});
return result;
}
I gave your form inputs some name attributes. Not sure if you added the actual code to your page, so I did so here. I added a button to trigger just for a demo. I added the simplest bit of CSS.
$("#validateme").on('click', function() {
console.log("validating");
let Validator = $("#addMapForm").validate();
Validator.form();
console.log(Validator.valid());
});
.error { color:red}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/jquery.validate.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/additional-methods.min.js"></script>
<form enctype="multipart/form-data" action="/Admin/AddMap" method="post" id="addMapForm">
<div>
<br />
<br />
<div class="col-md-12">
<div class="form-group">
<label>Location Name *</label>
<input class="form-control" name="location" required type="text"/>
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label>Unit/ Floor Number</label>
<input class="form-control" />
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label>Address*</label>
<textarea class="form-control" name="address" style="height:100px" required></textarea>
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label>Town/ City *</label>
<input class="form-control" required type="text"/>
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label>Zip Code*</label>
<input class="form-control" name="zip" required />
</div>
</div>
</div>
<button id="validateme" type="button">Do validate</button>
</form>
I have two inline radio button in a form using Bootstrap. But when I validate it then the message showing inside of first radio button instead of showing after second radio button. I would like to show that radio button message like Email and password. Here is the screenshot of my form.
Without Validation:
With Validation:
HTML Form:
<form name="registration" action="">
<div class="signingInner">
<h4 style="font-weight: 500; text-align:center; font-size: 20px ">Sign in to your Account</h4>
<div class="form-group">
<label for="emailId">Email Address:</label>
<input type="text" class="form-control" id="login_email" name="login_email" placeholder="Please enter Email address">
</div>
<div class="form-group">
<label for="pwd">Password:</label>
<input type="password" class="form-control" name="login_password" id="login_password" placeholder="●●●●●●">
</div>
<div class="form-group">
<div class="radio-inline" style="padding-left: 100px;">
<input type="radio" id="user" name="LoginMode" value="user" >
As <strong>User</strong> </>
</div>
<div class="radio-inline" style="padding-left: 30px;">
<input type="radio" id="company" name="LoginMode" value="company" >
As <strong>Company</strong></>
</div>
</div>
<input type="submit" name="btnLogin" class="btn btn-lg btn-primary btn-block" value="Login"></input>
</div>
</form>
Plunker Link:
https://plnkr.co/edit/0vpvU9QbRu8Mlwbi04ti?p=preview
The trick is to use errorPlacement callback function.
So I am checking whether the rendered type is radio button then I am tracking the appropriate topmost parent div and inserting the message after that.
errorPlacement: function(error, element) {
if ( element.is(":radio") ) {
error.insertAfter( element.parent().parent().parent().parent());
}
else { // This is the default behavior of the script for all fields
error.insertAfter( element );
}
},
See the updated plunkr here.
And the output looks like
EDIT:
I have finally updated the original plunkr provided by you.
I am working on application where I've one form and It should show validation error message for input fields on wrong input.
My form will look like this -
It should show error message if -
Input field modified with wrong input
Submit button clicked without modification in required input field.
It should show error message as below -
To achieve this I am using ng-message directive. It wil help me to show error message on $dirty of input field. But for Submit button I could not find correct way. Currently I am using a flag which will be modified on submit click. But I am interested in some better approach. Is there predefined method available to achieve this ?
Here is the complete example which I tried, and here is plunkr for the same.
<!doctype html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.0-rc.0/angular.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.0-rc.0/angular-messages.js"></script>
<script>
var app = angular.module('myApp', ['ngMessages']);
app.controller('myCtrl', function($scope) {
$scope.submitForm = function() {
$scope.submitted = true;
if (myForm.$valid) {
alert('Form submitted with passed validation');
}
};
});
</script>
</head>
<body ng-app="myApp" ng-controller="myCtrl">
<form name="myForm" novalidate ng-submit="submitForm()">
<label>
Enter your name:
<input type="text" name="myName" ng-model="name" ng-minlength="5" ng-maxlength="20" required />
</label>
<div ng-if="submitted || myForm.myName.$dirty" ng-messages="myForm.myName.$error" style="color:red" role="alert">
<div ng-message="required">You did not enter a field</div>
<div ng-message="minlength">Your field is too short</div>
<div ng-message="maxlength">Your field is too long</div>
</div>
<br>
<br>
<label>
Enter your phone number:
<input type="number" name="myPhone" ng-model="phone" ng-maxlength="20" required />
</label>
<div ng-if="submitted || myForm.myPhone.$dirty" ng-messages="myForm.myPhone.$error" style="color:red" role="alert">
<div ng-message="required">You did not enter a field</div>
<div ng-message="maxlength">Your field is too long</div>
</div>
<br>
<br>
<button type="submit">Submit</button>
</form>
</body>
</html>
Thanks!
You can use $submitted for the form,
Syntax: formname.$submitted
$submitted : True if user has submitted the form even if its invalid.
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.0-rc.0/angular.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.0-rc.0/angular-messages.js"></script>
<script>
var app = angular.module('myApp', ['ngMessages']);
app.controller('myCtrl', function($scope) {
$scope.submitForm = function() {
if (myForm.$valid) {
alert('Form submitted with passed validation');
}
};
});
</script>
</head>
<body ng-app="myApp" ng-controller="myCtrl">
<form name="myForm" novalidate ng-submit="submitForm()">
<label>
Enter your name:
<input type="text" name="myName" ng-model="name" ng-minlength="5" ng-maxlength="20" required />
</label>
<div ng-if="myForm.$submitted || myForm.myName.$dirty" ng-messages="myForm.myName.$error" style="color:red" role="alert">
<div ng-message="required">You did not enter a field</div>
<div ng-message="minlength">Your field is too short</div>
<div ng-message="maxlength">Your field is too long</div>
</div>
<br>
<br>
<label>
Enter your phone number:
<input type="number" name="myPhone" ng-model="phone" ng-maxlength="20" required />
</label>
<div ng-if="myForm.$submitted || myForm.myPhone.$dirty" ng-messages="myForm.myPhone.$error" style="color:red" role="alert">
<div ng-message="required">You did not enter a field</div>
<div ng-message="maxlength">Your field is too long</div>
</div>
<br>
<br>
<button type="submit">Submit</button>
</form>
</body>
</html>
Please run this snippet and check.
Here is the reference
The changed plunker link of yours
Update Plunker Link
You could go with disabling submit button till your form isn't correct one
I am working with AngularJS and have a form with ng-submit in it:
<div ng-controller="LoginController as vm">
<form class="login-form" name="vm.form" ng-submit="vm.login()">
<h3 class="form-title">Sign In</h3>
<div class="form-group">
<label class="control-label">E-mailaddress</label>
<input class="form-control" type="text"
name="email" ng-model="vm.email"/>
</div>
<div class="form-group">
<label class="control-label">Password</label>
<input class="form-control" type="password" name="password" ng-model="vm.password"/>
</div>
<div class="form-actions">
<button type="submit" class="btn btn-success uppercase">Login</button>
</div>
</form>
</div>
The issue: When I click manually on Login, everything works just fine. ng-submit is correctly used by calling vm.login(). However, when I press the enter key, ng-submit isn't called. I've search for a long time, watched examples, read issues at GitHub but can't figure this out... Any suggestions?
Edit
The requested controller-code:
angular.module('app').controller('LoginController', function LoginController(LoginFactory, $state) {
'use strict';
var vm = this;
vm.login = login;
function login() {
console.log('login');
LoginFactory.login(vm.email, vm.password).then(function success(response) {
LoginFactory.setUser(response.data.data.user);
vm.user = response.data.data.user;
var savedState = LoginFactory.getOnLoginState();
$state.go(!savedState.state ? 'root.dashboard' : savedState.state, savedState.stateParams);
}, handleError);
}
});
It is not going to work that way, as we can check on Angular's docs:
if a form has 2+ input fields and no buttons or input[type=submit] then hitting enter doesn't trigger submit
As a workaround, I would suggest using two form tags, one to each field, both using the same function in ng-submit, something like:
<div ng-controller="LoginFactory">
<form class="login-form" ng-submit="vm.login()">
<h3 class="form-title">Sign In</h3>
<div class="form-group">
<label class="control-label">E-mailaddress</label>
<input class="form-control" type="text"
name="email" ng-model="vm.email"/>
</div>
</form>
<form class="login-form" ng-submit="vm.login()">
<div class="form-group">
<label class="control-label">Password</label>
<input class="form-control" type="password" name="password" ng-model="vm.password"/>
</div>
<div class="form-actions">
<button type="submit" class="btn btn-success uppercase">Login</button>
</div>
</form>
</div>
Alternatively You can also solve it by building the ng-enter directive and use it. Below is the code snippet to do so.
angular.module('myApp').directive('ngEnter', function () {
return function (scope, element, attrs) {
element.bind('keydown keypress', function (event) {
if(event.which === 13) {
scope.$apply(function (){
scope.$eval(attrs.ngEnter);
});
event.preventDefault();
}
});
};
});
I have tried to your code assuming your controller as provided below and its working as expected. Give it a try:
<!DOCTYPE html>
<html lang="en" ng-app="app">
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript" src="js/angular.min.js"></script>
</head>
<body>
<div ng-controller="LoginFactory">
<form class="login-form" name="vm.form" ng-submit="vm.login()">
<h3 class="form-title">Sign In</h3>
<div class="form-group">
<label class="control-label">E-mailaddress</label>
<input class="form-control" type="text"
name="email" ng-model="vm.email"/>
</div>
<div class="form-group">
<label class="control-label">Password</label>
<input class="form-control" type="password" name="password" ng-model="vm.password"/>
</div>
<div class="form-actions">
<button type="submit" class="btn btn-success uppercase">Login</button>
</div>
</form>
</div>
<script type="text/javascript">
'use strict';
angular.module('app', []).controller('LoginFactory', function LoginController($scope){
$scope.vm={};
$scope.vm.login=login;
function login(){
console.log('login');
}
});
</script>
</body>
</html>