I had a input field in my form that have the following class:
class="form-group field-sale-first_name required"
and after client side validation it can have one of two different classes added to it.
class="form-group field-sale-first_name required has-success"
or
class="form-group field-sale-first_name required has-error"
I'm trying to catch when this class has success of error status with jQuery method hasClass() but always getting True even when the .has-error or the has-success are not there.
<form id="checkout-form" action="/site/checkout" method="post">
<div class="form-group field-sale-first_name required">
<input type="text" id="sale-first_name" class="form-control" name="Sale[first_name]" placeholder="First Name">
and the script:
clientValidationStatus = (function() {
if ($("form-group.field-sale-first_name.required").hasClass(".has-success)) {
alert("Success");
}
})();
Could someone give a hint of how to get this change?
Thanks in advance.
You are missing hasClass syntax hasClass("has-success") and for form-group
clientValidationStatus = (function() {
if ($(".form-group.field-sale-first_name.required").hasClass("has-success")) {
alert("Success");
}
})();
Related
I have been battling with what is wrong on this code since. It so happens that the form is not submitting on this button. The button is of type button and not in the form tag.
$("#step1Btn").click(function () {
var userForm = $("form[name='step1Form']");
if (userForm.valid()) {
userForm.submit(function () {
console.log('submitted o!')
$("#spin1").show();
$("form[name='step1Form'] > span").remove();
$('input[name="emailInput"]').prop('name', "id")
$('input[name="fullNameInput"]').prop('name', "full-name")
$('input[name="phoneInput"]').prop('name', "phone-number")
$.ajax({
type: 'POST',
url: "api/v1/user?" + $(this).serialize(),
success: (result) => {
localStorage.setItem('user', JSON.stringify(result))
localStorage.setItem('authToken', result.authToken);
$("form[name='step1Form'] > span").remove()
$('#step1, #step2').toggle();
$('#step1Title, #step2Title').toggle();
},
error: function (request, exception, errorThrown) {
$("form[name='step1Form'] > span").remove();
$("form[name='step1Form']").prepend('<span class=\'error\'><p>' + request.responseJSON.message + '</p></span>')
},
})
});
} else {
return false;
}
});
Below is the complete form
<div id="step1" class="col-12 col-md-6">
<form name="step1Form">
<div class="home-icon d-flex justify-content-center align-items-center flex-column">
<img src="images/new-icons/user.png" alt="User Registration logo" height="80" />
<p class="my-3">User Registration</p>
</div>
<div class="form-group">
<label for="fullNameInput">Contact full name</label>
<input name="fullNameInput" class="form-control custom-input" placeholder="First name Last name" id="fullNameInput">
</div>
<div class="form-group">
<label for="emailInput">Contact email address</label>
<input name="emailInput" type="email" placeholder="example#email.com" class="form-control custom-input" id="emailInput">
</div>
<div class="form-group">
<label for="confirmEmailInput">Confirm contact email address</label>
<input name="confirmEmailInput" type="email" placeholder="example#email.com" class="form-control custom-input"
id="confirmEmailInput">
</div>
<div class="form-group">
<label for="phone">Contact phone number</label>
<input name="phoneInput" placeholder="08012345678" class="form-control custom-input" id="phone">
</div>
</form>
<button type="button" class="btn red-btn user-btn custom-btn" id="step1Btn">Next<i id="spin1" class="fa fa-spinner fa-spin"></i></button>
</div>
So I would like to see where I went wrong. I am able to log and see output whenever i place a console.log in between the if(userForm.valid) and the userForm.submit().
But as soon as i place it in the userform.submit() I do not get any value back. Like, the form is totally not submitting. I dont know if its because of how I made my Ajax call.. Please Help
You're putting Ajax inside of a submit....
$("#step1Btn").click(function () {
....
if (userForm.valid()) {
userForm.submit(function () {
....
$.ajax({ ....
Which makes no sense since Ajax replaces the actual submit. By doing this you are effectively sending it through validation again; I can't see the .validate() method, but suspect that you are simply using the default option, which would be yet another regular submit... you're probably stuck in a loop going nowhere.
The best place for your Ajax would be inside the submitHandler of the .validate() method.
If your button is outside of the form, you capture the click and manually trigger a submit, which then lets the validation plugin take over the rest.
$("#step1Btn").click(function () { // click of external button
$("form[name='step1Form']").submit(); // trigger validation & submission
});
$("form[name='step1Form']").validate({ // initialize plugin
submitHandler: function(form) { // fires when valid
// YOUR AJAX GOES INSIDE HERE
return false;
},
// other options, rules, etc.
});
Read the documentation for the submitHandler.
This is my first time using AngularJS, and the form validation is making me question my sanity. You would think this would be the easy part, but no matter how many ways I've tried Googling, the only thing that works is if I set a flag inside my controller's submit if the form is invalid to set the error class. I've looked at similar problems here, but none of them helped, so please do not simply dismiss this as a potential duplicate. Everything else has been a fail.
In the example mark up below I have reduced my form down to just one element. Here is what I have observed:
Using only $error.required does work. The ng-class { 'has-error' :registerForm.firstName.$error.required} does outline the text box with the bootstrap has-ertror class, but this is on form load, which I do not want.
The <p> element with the error message will exhibit the same behavior, so I know that the message exists and is not malfored. It will also display if I only use $error.required. But as soon as I add && registerForm.$submitted ( or $isdirty or !notpristine ) the message will not display on form submit. There are no errors (have developers tools open in chrome) and will post to the web API with no problem and return ok 200 or 400 if I send bad params.
I can write validation code inside my controller, checking if the field has a value and setting a flag on $scope such as $scope.firstNameIsRequired and that will work fine setting ng-show="$scope.firstNameIsRequired", but that will remove testability.
So the problem definitely has to be with how I am adding this in the markup. But after a weekend spent googling I am at my wits end. The only other thing different is that I am using a span on a click element to submit the form instead of an input = submit, but the registerForm.$valid function is setting the correct value. Do I somehow need to trigger the form validation in that ng-click directive?
I am using angular.js v 1.4.8.
I do have angular ui which has it's own validate, but that shouldn't interfere with the basic validation.
Here is the simplified markup:
<form name="registerForm" class="form-group form-group-sm"
ng-controller="userAccountController" novalidate>
<div class="form-group"
ng-class="{ 'has-error' : registerForm.firstName.$error.required }">
<div><label>First Name</label> </div>
<input type="text" class="form-control" id="firstName" name="firstName" value=""
ng-model="firstName" placeholder="First Name" maxlength="100" required=""/>
<p ng-show="registerForm.firstName.$error.required && registerForm.$submitted"
class="alert alert-danger">First Name is required</p>
</div>
<div>
<span class="btn btn-default"
ng-click="submit(registerForm.$valid)">Register</span>
</div>
My controller code is
angular.module( "Application" ).controller( "userAccountController", [
"$scope", "userAccountService", function ( $scope, userAccountService)
{
$scope.hasErrors = false;
$scope.errorMessages = "";
$scope.emailExists = true;
$scope.clearErrors = function (){
$scope.hasErrors = false;
}
$scope.onSuccess = function ( response ) {
alert( "succeeded" );
}
$scope.submit = function (isValid) {
if ($scope.registerForm.$invalid)
return;
alert("isvalid");
$scope.clearErrors();
var userProfile = $scope.createUser();
userAccountService.registerUser(userProfile, $scope.onSuccess, $scope.onError);
}
$scope.createUser = function () {
return {
FirstName: $scope.firstName, LastName: $scope.lastName, Email: $scope.email,
Password: $scope.password, SendAlerts: $scope.sendAlerts
};
};
}
]);
Any help will be appreciated. I probably just need a second set of eyes here because I have been dealing with this on and off since late Friday.
in angular you want use the element.$valid to check wheter an model is valid or not - and you use element.$error.{type} to check for a specific validation error.
Keep in mind that the form.$submitted will only be set if the form is actually submitted - and if it has validationerrors it will not be submitted (and thus that flag is still false)
If you want to show errors only on submit you could use a button with type="submit" and bind to ng-click event - and use that to set a flag that the form has been validated. And handling the submit if the form is valid.
A short example with 2 textboxes, having required and minlength validation:
angular.module("myApp", [])
.controller("myFormController", function($scope) {
$scope.isValidated = false;
$scope.submit = function(myForm) {
$scope.isValidated = true;
if(myForm.$valid) {
console.log("SUCCESS!!");
}
};
});
.form-group {
margin: 10px;
padding: 10px;
}
.form-group.has-error {
border: 1px solid red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular.js"></script>
<div ng-app="myApp" ng-controller="myFormController">
<form name="myForm">
<div class="form-group" ng-class="{'has-error': myForm.name.$invalid && isValidated}">
<span>Name:</span>
<input type="text" name="name" minlength="5" ng-model="name" required />
<span ng-if="myForm.name.$error.required && isValidated">Name is required</span>
<span ng-if="myForm.name.$error.minlength && isValidated">Length must be atleast 5 characters</span>
</div>
<div class="form-group" ng-class="{'has-error': myForm.email.$invalid && isValidated}">
<span>Email:</span>
<input type="text" name="email" minlength="5" ng-model="email" required />
<span ng-if="myForm.email.$error.required && isValidated">Email is required</span>
<span ng-if="myForm.email.$error.minlength && isValidated">Length must be atleast 5 characters</span>
</div>
<button type="submit" ng-click="submit(myForm)">Submit</button>
</form>
</div>
I want my input always has value so that focus is fixed to it until the values are typed and the cursor also can't escape the input.
I know the focus() function is existed but how can i deal with it? It is just an event isn't it? Is there any solution?
This is the html code which include the input.
<div class="col-xs-3 vcenter from-group" id="info">
<div class="form-group">
<label class="control-label" for="inputID">아이디</label><p style="display:inline; padding-left:60px; color:red; font-size: 12px">* 적어도 하나의 대문자, 소문자, 숫자를 포함한 6자~16자</p>
<div class="controls">
<input type="text" class="form-control" name="inputID" id="inputID" placeholder="내용을 입력해 주세요" required autofocus>
</div>
</div>
This is the script where the input is bound the events.
<script>
jQuery('#inputID').keyup(blank_special_char_validation);
jQuery('#inputID').focusout(function(){
if (!$(this).val()) {
var message = "no id";
error(this.id, message); // ** TODO : SET FOCUS HERE !!
} else {
id_form_validation(this.id);
}
});
Could you guys see the **TODO in code above? I want to add function that the focus is fixed until the value is written.
Please could guys give me some idea. Thank you.
=========================================================================
I want to focus my input depends on situation. For example, I want to focus it when the value isn't existed or the validation doesn't correct. However it has to focus out when the value is existed or the validation is true.
I can set focus it finally but how can i unfocus it? I mean i want to untrigger the focus event.
jQuery('#inputID').on('blur',function(){
if (!$(this).val()) {
var message = "아이디를 입력해 주세요";
error(this.id, message);
$(this).focus();
} else {
//$(this).focus();
if (!id_form_validation(this.id)) {
$(this).focus(); // TODO : FOCUS
}else {
$(this).off('focus'); // TODO : FOCUS OUT
$(this).off('blur');
}
}
});
You can use this code to do the same... I have used blur
//jQuery('#inputID').keyup(blank_special_char_validation);
jQuery('#inputID').focusout(function() {
if (!$(this).val()) {
$(this).focus();
var message = "no id";
error(this.id, message);
}else {
id_form_validation(this.id);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-xs-3 vcenter from-group" id="info">
<div class="form-group">
<label class="control-label" for="inputID">아이디</label><p style="display:inline; padding-left:60px; color:red; font-size: 12px">* 적어도 하나의 대문자, 소문자, 숫자를 포함한 6자~16자</p>
<div class="controls">
<input type="text" class="form-control" name="inputID" id="inputID" placeholder="내용을 입력해 주세요" required autofocus>
</div>
</div>
Use $(this).focus() to focus your input.
focus() with no arguments will trigger that event on an element.
i'm on my web site project and it seems that my jquery function doesn't work
.i have to validate this:if the user enters <<nom de famille du pere>>,<<prenom du pere>> has to be entered too.This is my html code:
<div class="form-group">
<div class="col-md-6">
<label class="col-md-4 control-label" for="father">Nom de famille du père </label>
<input id="father" name="father" type="text" class="form-control input-md" >
</div>
</div><br/><br/><br/>
<div class="form-group">
<div class="col-md-6">
<label class="col-md-4 control-label" for="ffather">Prénom du père</label>
<input id="ffather" name="ffather" type="text" class="form-control input-md">
</div>
</div><br/><br/><br/>
and this is my jquery function :
$(document).ready(function() {
$('#father').submit(function() {
if ($(this)).is(':empty')) {
$('#ffather').prop('required',false);
}
else{
$('#ffather').prop('required',true);
}} }
DEMO: http://jsfiddle.net/Lfnrrdfu/1/
you have a few mistakes in your code:
$('#father').on('keyup', function () {
if (!$(this).val()) {
$('#ffather').prop('required',false);
}
else{
$('#ffather').prop('required',true);
}
console.log($('#ffather').prop('required'));
});
You can't use submit event with an input, submit is for a form, you could use the form but then you have to prevent default then check the value of the input.
You are trying to set the attributes upon form submission, which is not the right way to do it. You should only check if the fields satisfy the requirements on submit. Defining the constrains should be on the markup. If you are not using any custom form validator, you can use HTML constrain validation. Examples can be found here
http://www.w3schools.com/js/js_validation.asp
Again, the jQuery submit event can ONLY be attached to form elements. Review here https://api.jquery.com/submit/
I'm dealing with a standard "change your password" form where you have two fields: password1 and password2. Those two fields are just to validate that the user enter the right password and they need to contain the same text.
I added a directive to validate password but now I want that, if both fields are not equal between each other, make both fields become invalid and not just the one I'm typing in. Can I do that?
I try to call the $setValidity on both ngmodels but I'm not finding the way to call from one ctrl.$parsers.unshift or directive link function the $setValidity or the other field I'm not currently validating. I'm really lost..
Thanks a lot!
My directive is:
myApp.directive('validatepassword', function () {
return {
require: 'ngModel',
restrict: 'A', // only activate on element attribute
link: function (scope, elm, attrs, ngModel) {
ngModel.$parsers.unshift(function (viewValue) {
var valPasswordValue = attrs.validatepassword;
var otherPassword = $('#' + valPasswordValue)[0].value;
var valido = scope.validatePassword(viewValue, otherPassword);
ngModel.$setValidity('password', valido);
return viewValue;
});
}
};
});
and I'm using in this way in the code:
<div class="control-group">
<label class="control-label" for="inputPassword1">Password</label>
<div class="controls">
<input id="inputPassword1" name="inputPassword1" type="password" ng-model="context.Password" required validatepassword="inputPassword2"/>
<span class="alert-danger invalid-form" ng-show="!addEditForm.inputPassword1.$valid">(*)</span>
</div>
</div>
<div class="control-group">
<label class="control-label" for="inputPassword2">Repeat Password</label>
<div class="controls">
<input id="inputPassword2" name="inputPassword2" type="password" ng-model="context.Password2" required validatepassword="inputPassword1"/>
<span class="alert-danger invalid-form" ng-show="!addEditForm.inputPassword2.$valid">(*)</span>
</div>
</div>
Any ideas about how can I validate both fields as soon as one of them change?
Thanks a lot!
To trigger the validation method from one field in another field I had to manually set the value of the other field. You can do that inside of a ng-change:
ng-change="addEditForm.inputPassword2.$setViewValue(addEditForm.inputPassword2.$viewValue)"
When you do that it should trigger the validation in both password fields.
You could also access the fields inside of your directive like so:
scope.addEditForm.inputPassword1
So you could get rid of the jQuery access inside of your directive.
Here is the HTML-partial that worked for password validation on both fields:
<div class="control-group">
<label class="control-label" for="inputPassword1">Password</label>
<div class="controls">
<input id="inputPassword1" name="inputPassword1" type="password" ng-model="context.Password" required
validatepassword="inputPassword2" ng-change="addEditForm.inputPassword2.$setViewValue(addEditForm.inputPassword2.$viewValue)"/>
<span class="alert-danger invalid-form" ng-show="!addEditForm.inputPassword1.$valid">(*)</span>
</div>
</div>
<div class="control-group">
<label class="control-label" for="inputPassword2">Repeat Password</label>
<div class="controls">
<input id="inputPassword2" name="inputPassword2" type="password" ng-model="context.Password2" required
validatepassword="inputPassword1" ng-change="addEditForm.inputPassword1.$setViewValue(addEditForm.inputPassword1.$viewValue)"/>
<span class="alert-danger invalid-form" ng-show="!addEditForm.inputPassword2.$valid">(*)</span>
</div>
</div>
Angular-UI has a built-in validator which you can use in various purpose, there is a exact example of password and confirm password which you can check:
https://github.com/angular-ui/ui-utils/blob/master/modules/validate/demo/index.html#L29
Please check this fiddle
http://jsfiddle.net/vigneshvdm/Dnt7w/5/
you can do something like this
var password=$("#telephone").val();
var reenteredpassword=$("#mobile").val();
if(password==reenteredpassword)
{
$("#required").html("Passwords Match");
}
else
{
$("#required").html("Passwords do not Match");
}