$(document).ready(function () {
jQuery.validator.addMethod("insz", function (value, element) {
var insz = $('#txtINSZ').val()
var controle = parseInt(insz.substring(13, 15))
var getal = insz.substring(0, 2) + insz.substring(3, 5) + insz.substring(6, 8) + insz.substring(9, 12)
var rest = parseInt(getal) % 97
alert("we doin' this mun")
return 97 - rest == controle;
}, "* Amount must be greater than zero");
$('#form1').validate({
rules: {
txtINSZ: {
required: $('#cbInsz').prop('checked') == false,
insz: function () {
$('#cbInsz').prop('checked') == true;
}
}
},
showErrors: function (errorMap, errorList) {
this.defaultShowErrors();// to display the default error placement
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.validation/1.16.0/jquery.validate.js"></script>
<form method="post" action="#" id="form1" a="" novalidate="novalidate">
<div id="container">
<div class="container-fluid">
<div class="col-xs-12">
<div class="form-horizontal col-xs-4" id="divDimLeft">
<span id="lblTitleAlgemeen">Algemen Informatie</span>
<div class="checkbox" style="margin-left:20px;">
<span id="lblCheck">
<input type="checkbox" id="cbInsz" checked="">
INSZ nummer werknemer gekend?
</span>
</div>
<div class="form-group" id="divINSZ">
<span id="lblINSZ" class="required" for="txtINSZ" aria-required="true">INSZ-nummer gekend?</span>
<input name="ctl00$ContentPlaceHolder1$txtINSZ" type="text" maxlength="15" id="txtINSZ" class="form-control required form valid" oninput="autoInvullen()" aria-required="true" placeholder="__.__.__-___.__" aria-invalid="false" required=""><label id="txtINSZ-error" class="error" for="txtINSZ" style="display: none;"></label>
</div>
<div class="form-group">
<span id="lblNaam" class="required" for="txtNaam" aria-required="true">Naam</span>
<input name="ctl00$ContentPlaceHolder1$txtNaam" type="text" maxlength="40" id="txtNaam" class="form-control form requiredField error" aria-required="true" aria-invalid="true"><label id="txtNaam-error" class="error" for="txtNaam">Dit veld is verplicht.</label>
</div>
<div id="divButton" class="text-right" style="width: 87.5%">
<input type="submit" name="ctl00$ContentPlaceHolder1$btnSubmit" value="Volgende" id="btnSubmit" class="btn btn-primary col-xs-2" style="float: none; min-width:200px;">
</div>
</div>
</div>
</div>
</div>
</form>
I wanted to make a custom validator but for some reason it's not working at all. The required does work so there is no issue with finding the elements in my page. So is there someone who has any idea why it is not working?
Thans in advance, under here you find the code i'm using including the method I wrote and the start of the validate method.
You can't just insert a comparison operator all by itself as the parameter; you need a function that returns the value of this parameter, in this case a boolean from the comparison operator...
$('#form1').validate({
rules: {
txtINSZ: {
required: function() {
return $('#cbInsz').prop('checked') == false;
},
insz: function() {
return $('#cbInsz').prop('checked') == false;
}
....
Solved it, I just putted the rules out of the rules section. After the validation code I putted this:
$('#txtINSZ').rules("add", {
required:true,
insz:true
})
Works perfectly.
I also faced the same situation, but in my case below two steps worked.
use data-rule-insz="true" attribute on your HTML input element for which you want custom validation.
also add a name attribute as mentioned in the below example:-
<input id="customer" name="customer" data-rule-insz="true" required type="text" class="typeahead form-control" />
Related
This question already has answers here:
Validate dynamic field jquery
(2 answers)
Closed 2 years ago.
I have to clone the certain section of form and have to implement same validation rules defined previously.
As I researched on this issue, almost all them recommended to add new rules again in the newly generated elements. So, I had tried by adding new rule with following code
let $contactItem = $(".contact")
.first()
.clone()
.insertAfter($(".contact").last());
$contactItem.find("input").each(function(){
$(this).rules("add", {
required : true,
messages : { required : 'field is required.' }
});
});
But my bad luck, this technique did not solve my issue. So I am looking for another solution for it.
Some details on library I am using:
jQuery v1.9.1
jQuery Validation Plugin v1.17.0
$(document).ready(function() {
let $validator;
$("#btnAddNew")
.off("click")
.on("click", function() {
let $contactItem = $(".contact")
.first()
.clone()
.insertAfter($(".contact").last());
});
$validator = $("#contactForm").validate({
rules: {
firstName: {
required: true
},
lastName: {
required: true
}
},
messages: {
firstName: {
required: "* Required"
},
lastName: {
required: "* Required"
}
},
ignore: ":hidden, :disabled"
});
$("#btnSave")
.off("click")
.on("click", function() {
if ($validator.form()) {
console.log("ok");
}
});
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/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://cdn.jsdelivr.net/npm/jquery-validation#1.19.2/dist/jquery.validate.js"></script>
<div class="container">
<form id="contactForm">
<div class="contact">
<h5 class="card-title">Contact Info</h5>
<div class="form-row">
<div class="form-group col-md-6">
<label for="inputEmail4">First Name</label>
<input type="text" class="form-control" name="firstName" placeholder="Your First Name">
</div>
<div class="form-group col-md-6">
<label for="inputEmail4">Last Name</label>
<input type="text" class="form-control" name="lastName" placeholder="Your Last Name">
</div>
</div>
</div>
<button type="button" id="btnAddNew" class="btn btn-primary">Add Next</button>
<button type="button" id="btnSave" class="btn btn-primary">Save</button>
</form>
</div>
Just adding required to the elements is probably the simplest solution and modify the default message.
I've also commented out an approach for setting class rules.
Note you also need to modify the names in order for them to be unique. I've used very simple incremental logic , modify if you will be adding and removing
$.extend($.validator.messages, {
required: "* required."
})
// Alternate using class rules
/*jQuery.validator.addClassRules("name-field", {
required: true
});*/
$(document).ready(function() {
let $validator;
$("#btnAddNew")
.off("click")
.on("click", function() {
let $contact = $(".contact");
let $contactItem = $contact
.first()
.clone()
.insertAfter($(".contact").last());
// increment input names
$contactItem.find('input').attr('name', function(_, curr) {
return curr + $contact.length
});
});
$validator = $("#contactForm").validate();
$("#btnSave")
.off("click")
.on("click", function() {
if ($validator.form()) {
console.log("ok");
}
});
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/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://cdn.jsdelivr.net/npm/jquery-validation#1.19.2/dist/jquery.validate.js"></script>
<div class="container">
<form id="contactForm">
<div class="contact">
<h5 class="card-title">Contact Info</h5>
<div class="form-row">
<div class="form-group col-md-6">
<label for="inputEmail4">First Name</label>
<input type="text" class="form-control name-field" name="firstName" placeholder="Your First Name" required>
</div>
<div class="form-group col-md-6">
<label for="inputEmail4">Last Name</label>
<input type="text" class="form-control name-field" name="lastName" placeholder="Your Last Name" required>
</div>
</div>
</div>
<button type="button" id="btnAddNew" class="btn btn-primary">Add Next</button>
<button type="button" id="btnSave" class="btn btn-primary">Save</button>
</form>
</div>
I want to apply required field validation on text box group in which at least one text box group must contain value.
in bellow image, details of at least one bank must be filled.
I have used jquery-form-validator plugin from http://www.formvalidator.net/#custom-validators and created custome validator as bellow, but Its not working.
$("#txtBankDetails")
.valAttr('error-msg', 'select atlest 1 bankname.');
$.formUtils.addValidator({
name: 'data-text-group',
validatorFunction: function (value, $el, config, language, $form) {
debugger
var isValid = true,
// get name of element. since it is a checkbox group, all checkboxes will have same name
elname = $el.attr('data-text-group'),
// get checkboxes and count the checked ones
$textBoxes = $('input[type=textbox][data-text-group^="' + elname + '"]', $form),
nonEmptyCount = $textBoxes.filter(function () {
return !!this.value;
}).length;
alert(nonEmptyCount);
if (nonEmptyCount == 0) {
isValid = false;
}
}
});
// Setup form validation only on the form having id "registration"
$.validate({
form: '#registration',
modules: 'date, security, file, logic',
validateOnBlur: true,
showHelpOnFocus: true,
addSuggestions: true,
onModulesLoaded: function () {
console.log('All modules loaded!');
},
onSuccess: function ($form) {
form.submit();
alert("sucess")
return false;
},
onError: function () {
alert("Error")
}
});
html code is,
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<link href="//cdnjs.cloudflare.com/ajax/libs/jquery-form-validator/2.3.26/theme-default.min.css"
rel="stylesheet" type="text/css" />
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery-form-validator/2.3.26/jquery.form-validator.min.js"></script>
<form id="registration" method="post" action="#Url.Action("NewRegistration", "StaticPage")" enctype="multipart/form-data" class='has-validation-callback'>
<div class="container">
<div class="row">
<div class="col-md-4">
<input id="txtBankDetails" name="Bankname1" data-text-group="BankName" placeholder="01. BANK NAME" data-validation-error-msg="select atlest 1 bankname.">
</div>
<div class="col-md-4">
<input class="nwresmainfild" name="BankACNo1" placeholder="BANK A/C NO.">
</div>
<div class="col-md-4">
<input class="nwresmainfild" name="BankAddress1" placeholder="BANK ADDRESS">
</div>
</div>
<div class="row">
<div class="col-md-4">
<input id="txtBankDetails" name="Bankname2" data-text-group="BankName" placeholder="01. BANK NAME" data-validation-error-msg="select atlest 1 bankname.">
</div>
<div class="col-md-4">
<input name="BankACNo2" placeholder="BANK A/C NO.">
</div>
<div class="col-md-4">
<input name="BankAddress2" placeholder="BANK ADDRESS">
</div>
</div>
<div class="row">
<div class="col-md-4">
<input id="txtBankDetails" name="Bankname3" data-text-group="BankName" placeholder="03. BANK NAME" >
</div>
<div class="col-md-4">
<input name="BankACNo3" placeholder="BANK A/C NO.">
</div>
<div class="col-md-4">
<input name="BankAddress3" placeholder="BANK ADDRESS">
</div>
</div>
</div>
<input value="PROCESS & PRINT" class="green-btn uppercase" type="submit" id="btnSubmit" />
</form>
I am not able to see error message on clicking the submit button using angularjs.
Any lead will be appreciated
Thanks in advance :)
<form id="formbody" ng-submit="submituser(form)" name="form" novalidate>
<input type="text" ng-class="{ errorinput: submitted && form.dob.$invalid }" name="dob" ng-model="dob" placeholder="Date of Birth" required />
<span class="e" ng-show="submitted && form.dob.$invalid">Please provide a valid date of birth</span>
<div style="padding-left: 275px;">
<button type="submit">Submit</button>
<!-- <div type="button" id="btn" style="color: red;" >Submit</div> -->
</div>
</div>
</form>
.controller('ExampleController', function($scope, $location, $scope, $stateParams) {
$scope.singleSelect = '';
$scope.goToPage = function() {
console.log("selectservice");
$location.path("/selectservice");
}
$scope.submituser = function($scope) {
if ($scope.form.$valid) {} else {
$scope.submitted = true;
}
}
})
change ng-show of span to
<span class="e" ng-show="submitted && form.dob.$invalid">Please provide a valid date of birth</span>
please check the form name
you have used two different names
name ="form" in form tag and used as signUpForm.dob in input field.
Check your ng-model to
<form id="formbody" ng-submit="submituser(form)" name="signUpForm" novalidate>
<input type="text" ng-class="{ errorinput: submitted && signUpForm.dob.$invalid }" name="dob" ng-model="form.dob" placeholder="Date of Birth" required />
<span class="e" ng-if="submitted && signUpForm.dob.$invalid">Please provide a valid date of birth</span>
<div style="padding-left: 275px;">
<button type="submit">Submit</button>
</div>
</div>
</form>
.controller('ExampleController',function($scope,$location,$scope, $stateParams){
$scope.singleSelect='';
$scope.goToPage=function(){
console.log("selectservice");
$location.path("/selectservice");
}
$scope.submitted =false;
$scope.submituser = function(form){
// console.log(form);
if (form.$valid) {
your logic
} else {
$scope.submitted = true;
}
}
})
Try something like that
<link href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/css/bootstrap-combined.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="form" ng-app>
<div class="control-group" ng-class="{true: 'error'}[submitted && form.dob.$invalid]">
<label class="control-label" for="dob">Your Date of Birth</label>
<div class="controls">
<input type="text" name="dob" ng-model="dob" required />
<span class="help-inline" ng-show="submitted && form.dob.$invalid">Please provide a valid date of birth</span>
</div>
</div>
<button type="submit" class="btn btn-primary btn-large" ng-click="submitted=true">Submit</button>
</form>
You have to provide the form name but even after that you cannot refer to your form in controller unless you pass it through the submit function arguments. Also there is not signupForm() function in your controller.
The way to go is :
<form id="formbody" name="myForm" ng-submit="signupForm(myForm)" novalidate>
<!-- inputs etc -->
</form>
Then based on submituser():
$scope.signupForm = function(myForm) {
//Do whatever you want to do
if(myForm.$valid) {
//some logic
}else {
$scope.submitted = true;
}
}
On the other hand if you don't want to mess up with the controller you can always use FormController method $submitted. This would look like:
<span class="e" ng-show="myForm.$submitted && myForm.dob.$invalid">Please provide a valid date of birth</span>
I have successfully been able to use the code in
jsfiddle.net/y3qayufu/2/ to validate a group of fields but how can I display the error message in a specific location. I would like the error message to appear only once after the submit button has been pressed, preferably above the group, but possibly below.
Instead of this:
I would like this:
Thanks
Use jQuery validation errorPlacement function provided:
JsFiddle updated
$("#findproject_form").validate({
rules: {
....
},
errorPlacement: function(error, element) {
$('label.error').remove();
error.insertAfter("#submit_btn");
}
});
HTML:
<div class="searchbg" id="submit_btn" style="margin-right:0px;">
<input class="bgbttn" type="submit" name="submit" value="" />
</div>
Hi here is a fixed fiddle http://jsfiddle.net/bayahiassem/sdx4ru4s/2/
If you can't open it, here the updated code:
html Only added an id to the h3
<form id="findproject_form" method="post" action="{$BASE_URL}findproject">
<div class="bgtrans">
<h3 id="header">Search By</h3>
<div class="div_bg1">
<div class="searchbg">
<div class="seachbginputbg">
<input class="seachbginput validategroup" type="text" placeholder="Profession" id="Profession" name="Profession" value="" />
</div>
</div>
<div class="searchbg">
<div class="seachbginputbg">
<input class="seachbginput validategroup" type="text" placeholder="Location" id="Location1" name="Location1" value="" />
</div>
</div>
<div class="searchbg" style="margin-right:0px;">
<div class="seachbginputbg">
<input class="seachbginput validategroup" type="text" placeholder="Company" id="Company" name="Company" value="" />
</div>
</div>
<div class="clear"></div>
</div>
<div class="div_bg2">
<div class="searchbg">
<div class="seachbginputbg">
<input class="seachbginput validategroup" type="text" placeholder="Name" id="Name" name="Name" value="" />
</div>
</div>
<div class="searchbg">
<div class="seachbginputbg">
<input class="seachbginput validategroup" type="text" placeholder="Key Words" id="KeyWord" name="KeyWord" value="" />
</div>
</div>
<div class="searchbg" style="margin-right:0px;">
<input class="bgbttn" type="submit" name="submit" value="" />
</div>
<div class="clear"></div>
</div>
</div>
</form>
JS using errorPlacement :
$(document).ready(function () {
jQuery.validator.setDefaults({
debug: true,
success: "valid"
});
$("#findproject_form").validate({
rules: {
Profession: {
require_from_group: [1, ".validategroup"]
},
Location1: {
require_from_group: [1, ".validategroup"]
},
Company: {
require_from_group: [1, ".validategroup"]
},
Name: {
require_from_group: [1, ".validategroup"]
},
KeyWord: {
require_from_group: [1, ".validategroup"]
}
},
errorPlacement: function(error, element) {
console.log(error[0].innerText);
if(error[0].innerText == 'Please fill at least 1 of these fields.' && !errorshowed) {
error.insertAfter("#header");
errorshowed = true;
}
}
});
var errorshowed = false;
$.validator.addMethod("require_from_group", function (value, element, options) {
var $fields = $(options[1], element.form),
$fieldsFirst = $fields.eq(0),
validator = $fieldsFirst.data("valid_req_grp") ? $fieldsFirst.data("valid_req_grp") : $.extend({}, this),
isValid = $fields.filter(function () {
return validator.elementValue(this);
}).length >= options[0];
// Store the cloned validator for future validation
$fieldsFirst.data("valid_req_grp", validator);
// If element isn't being validated, run each require_from_group field's validation rules
if (!$(element).data("being_validated")) {
$fields.data("being_validated", true);
$fields.each(function () {
validator.element(this);
});
$fields.data("being_validated", false);
}
return isValid;
}, $.validator.format("Please fill at least {0} of these fields."));
});
Try this on submit u can put in function definition
var valid=0;
$(this).find('input[type=text], select').each(function(){
if($(this).val() != "") valid+=1;
});
if(valid==0)
{
$('#myDiv').html("please fil atleast one of these");
}
I need to check whether or not a input element's value(typed by the user into the box) returned from
$("#emailInput").css("value")
contains a certain string.
I have tried various methods seen on google but none have worked.
The HTML:
<form class="form-horizontal" role="form">
<div id="emailBorder">
<label id="emailStyle">Email address:</label>
<div id="emailInputStyle">
<input class="form-control" id="emailInput" type="text">
<span id="emailGlyphicon"></span>
</div>
</div>
<div class="form-group">
<label id="contentStyle">Content:</label>
<div id="contentInputStyle">
<textarea class="form-control" rows="5" id="contentInput"></textarea>
</div>
</div>
<button type="submit" id="sendStyle" class="btn btn-default">Send</button>
</form>
The Javascript (My Attempt):
$("#emailInput").change(function () {
if ($("#emailInput").css("value").contains("#") && $("#emailInput").css("value").contains(".")) {
// do something
} else {
// do something else
}
});
Instead of css(), use val(). Also, instead of contains() use indexOf() because contains() works on jQuery DOM objects, not strings
$("#emailInput").change(function() {
if ($("#emailInput").val().indexOf("#") > -1 && $("#emailInput").val().indexOf(".") > -1) {
console.log('It contains # and .');
} else {
// do something else
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form class="form-horizontal" role="form">
<div id="emailBorder">
<label id="emailStyle">Email address:</label>
<div id="emailInputStyle">
<input class="form-control" id="emailInput" type="text">
<span id="emailGlyphicon"></span>
</div>
</div>
<div class="form-group">
<label id="contentStyle">Content:</label>
<div id="contentInputStyle">
<textarea class="form-control" rows="5" id="contentInput"></textarea>
</div>
</div>
<button type="submit" id="sendStyle" class="btn btn-default">Send</button>
</form>
css() will get/set the inline style of an element. val() will get/set the value of an input type element
You can try this:
$("#emailInput").change(function () {
if ($this.contains("#") && $this.contains(".")) {
// do something
} else {
// do something else
}
});