Add or remove validation rules and message - javascript

I've below code and i trying to change validation rules and its message dynamically. But, i'm doing something wrong so that my code is not working as i want. i need to do when user select united state country then my validation rule will work for drop down of states and for any other countries the rule will work for input box of state field. but i am not able to change validation message dynamically also the rules not modifying properly
$(document).ready(function () {
var validator = $("#useform").validate({
rules: {
phone: {"required": true, "maxlength": 15, digits: true, "minlength": 10},
fax: {"required": true, "maxlength": 15, digits: true, "minlength": 10},
country:"required",
zip: {"required": true, "maxlength": 15,"minlength": 5},
},
messages: {
phone: {required:"Phone is required",maxlength:"Maximum 15 characters required",minlength:"Minimum 10 characters required"},
fax: {required:"Fax is required",maxlength:"Maximum 15 characters allowed",minlength:"Minimum 10 characters required"},
country: "Country is required",
state: "State is required",
zip: {digits:"ZIP should be numeric", required:"ZIP is required",maxlength:"Maximum 15 characters allowed",minlength:"Minimum 5 characters required"},
sel_state: {required: "State is required"},
}
});
if($('#country').val() == 'us')
{
$( "#zip" ).rules( "add", {
digits : true
});
}
else{
}
});
function checkCountryState(value) {
if($('#country').val() == 'us')
{
$('#state').hide();
$('#sel_state').show();
$( "#sel_state" ).rules( "add", {
required : true
});
$( "#state" ).rules( "remove",
"required"
);
}
else{
$('#state').show();
$( "#sel_state" ).rules( "remove", "required");
$( "#state" ).rules( "add",
{
required : true
}
);
$('#sel_state').hide();
}
}
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>
</head>
<form class="form-validate" action="" method="post" name="userform" id="userform" autocomplete="off">
<div class="row">
<div class="col-lg-12">
<div class="portlet ">
<div class="portlet-body">
<div class="row">
<div class="col-md-12 col-xl-8 my-xl-3">
<fieldset class="border h-100 my-xl-0">
<div class="row">
<div class="col-md-6 col-xl-4">
<div class="form-group">
<label class="control-label" for="phone">Phone:<span class="require">*</span></label>
<div class="input-icon right">
<input name="phone" value="" maxlength="15" id="phone" placeholder="Phone" type="text" class="form-control required">
</div>
</div>
</div>
<div class="col-md-6 col-xl-4">
<div class="form-group">
<label class="control-label" for="fax">Fax:<span class="require">*</span></label>
<div class="input-icon right">
<input name="fax" value="" id="fax" placeholder="Fax" type="text" class="form-control required" maxlength="15" >
</div>
</div>
</div>
<div class="col-md-6 col-xl-4">
<div class="form-group">
<label class="control-label" for="country">Country:<span class="require">*</span></label>
<div class="input-icon right">
<!-- remove_validation(this.id), renderStateForBilling(this.value);-->
<select name="country" id="country" class="form-control custom-select" onchange="checkCountryState(this.value);">
<option value="">--Select--</option>
<option value="us">Unieted States</option>
<option value="uk">Unieted Kingdom</option>
<option value="in">India</option>
</select>
</div>
</div>
</div>
<div class="col-md-6 col-xl-4">
<div class="form-group">
<label class="control-label" for="state">State:<span class="require">*</span></label>
<div class="input-icon right">
<input name="state" value="" id="state" type="text" class="form-control" style="display:none">
<select data-selected-state="" name="sel_state" id="sel_state" class="form-control custom-select required phone-group" >
<option>--Select--</option>
<option value="Alabam">Alabam</option>
<option value="Alaska">Alaska</option>
<option value="Arizona">Arizona</option>
</select>
</div>
</div>
</div>
<div class="col-md-6 col-xl-4">
<div class="form-group">
<label class="control-label" for="zip">Zip:<span class='require'>*</span></label>
<div class="input-icon right">
<input name="zip" value="" placeholder="Zip" id="zip" type="text" class="form-control " maxlength="15" >
</div>
</div>
</div>
</div>
</fieldset>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-lg-12 text-right px-0">
<div class="row mx-0">
<div class="col-md-12">
<input type="submit" class="btn btn-success" value="Save"/>
</div>
</div>
</div>
</div>
</form>

Use the depends option (vaguely documented under rules) as in:
rules: {
// ...
state: {
required: {
depends: el => $('#country').val() == 'us',
}
},
// ...
},
Dynamic messages can be done in a similar way (described under messages):
messages: {
// ...
state: {
required: el => {
if($('#country').val() == 'us') return 'State is required';
},
},
// ...
},

Related

Angular 8 ReactiveForm Input type "file" doesn't recognize value on Edge

I am using private _fb: FormBuilder to build my form in Angular 8. My form is initialized like this
this.itemForm = this._fb.group({
title: ['', [Validators.required, this._systemSvc.nonSpaceString]],
file: ['', Validators.required],
categories: [''],
tags: ['']
});
The template is
<form class="needs-validation" [formGroup]="itemForm" (ngSubmit)="createPost()">
<div class="form-row">
<div class="col-md-4 mb-3">
<div class="form-row mb-3">
<div class="col-md-12 mb-3">
<label class="text-primary"><strong>Title</strong></label>
<input type="text" formControlName="title" class="form-control"
[ngClass]="{ 'is-invalid': checkError('title') }">
<div *ngIf="checkError('title')" class="invalid-feedback">
<div *ngIf="f.title.errors.required">Title is required</div>
<div *ngIf="f.title.errors.whitespace">Title can't be blank space</div>
</div>
</div>
</div>
<div class="row mb-3">
<div class="col-md-6 mb-3">
<label class="text-primary"><strong>Categories</strong></label>
<select formControlName="categories" class="custom-select">
<option value="">--Select categories--</option>
<option value="Funny">Funny</option>
<option value="Music">Music</option>
<option value="Adventure">Adventure</option>
</select>
</div>
</div>
<div class="row mb-3">
<div class="col-md-12 mb-3">
<label class="text-primary" for="tags"><strong>Tags</strong></label>
<div>
<ng-container *ngFor="let tag of parsedTags;">
#{{tag}}
</ng-container>
</div>
<input id="tags" type="text" formControlName="tags" class="w-100"
(input)="onTagsChange($event.target.value)">
</div>
</div>
</div>
<div class="col-md-7 mb-3 offset-md-1">
<div class="form-row mb-3">
<div class="col-md-12 mb-3">
<label class="text-primary" for="upload"><strong>Choose file</strong></label>
<div class="custom-file">
<label class="custom-file-label" for="upload">Choose file</label>
<input type="file" class="custom-file-input" formControlName="file" id="upload"
(change)="handleFileInput($event.target.files)" accept="audio/*, video/*, image/*"
[ngClass]="{ 'is-invalid': checkError('file') }">
<div *ngIf="checkError('file')" class="invalid-feedback">
<div *ngIf="f.file.errors.required">File is required</div>
</div>
</div>
</div>
</div>
<div class="form-row mb-3">
<div class="col-md-12 mb-3">
<img *ngIf="uploadedFile" src="{{uploadedFile}}" class="w-100" id="previewImg">
</div>
</div>
</div>
</div>
<div class="form-row">
<div class="col-md-2 form-group">
<button type="button" id="cancelBtn" class="btn btn-primary mr-2" data-dismiss="modal">Cancel</button>
<button type="submit" class="btn btn-success">Post</button>
</div>
</div>
</form>
Every thing work well on Firefox and Chrome. But when it come to Edge, user select file but the reactive form doesn't recognize the selected file. Other controls like input = text and drop down are still ok on Edge. The form is invalid and say only the file is empty. This is the snapshot of the form
controls: Object
dirty: true
disabled: false
enabled: true
errors: null
invalid: true
parent: undefined
pending: false
pristine: false
root: Object
status: "INVALID"
statusChanges: Object
touched: true
untouched: false
updateOn: "change"
valid: false
validator: null
value: Object
categories: "Funny"
file: ""
tags: "asd"
title: "asd"
I had the same problem and I have resolved that by manualy set validation to null.
Create function in which check if input has file or not and inside it use below:
this.itemForm.controls['file'].setErrors(null)
It really works.

How would I be able to multiple select and pass data in the given format in vue js html?

I need to pass the data in the given format.
rules : [{
name:null,
section:null,
data : [{head:null,value:null}]
}],
This is the problem I am facing. Hope somebody could help me sort out a solution. The snippet is given. I need to pass data in the format given above. If another array is needed inside rules[], it is also fine
Is another array needed for head and value inside data[]. This will be also fine, if needed. Hoping for a help. Please help me to have a solution.
Please change the select to read the issues
addForm = new Vue({
el: "#addForm",
data: {
rules: [{
name: null,
section: null,
data: [{
head: null,
value: null
}]
}],
},
methods: {
addNewRules: function() {
this.rules.push({
name: null,
section: null,
data: [{
head: null,
value: null
}]
});
},
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.min.js"></script>
<div id="addForm">
<div class="card-content" v-for="(bok, index) in rules" :key="index">
<p>This is the first part which is fine for me</p>
<div class="row">
<div class="col-md-6">
<div class="form-group label-floating">
<label class="control-label">Act</label>
<select class="form-control" v-model="bok.name">
<option value="Act,1972">Act,1972</option>
<option value="Rule,2012">Rule,2012(CEMR)</option>
<option value="Act,1961">Act,1961</option>
</select>
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group label-floating">
<label class="control-label">Section</label>
<input type="text" class="form-control" v-model="bok.section">
</div>
</div>
<div class="row" v-if="bok.name == 'Act,1972'">
<p>When selecting Act,1972 is here rules.data.head. Fine for me</p>
<div class="col-md-4">
<div class="form-group label-floating">
<label class="control-label">Arms</label>
<input type="text" class="form-control" v-model="bok.data[0].head" required="">
</div>
</div>
</div>
<div class="row" v-if="bok.name == 'Rule,2012'">
<p>When Selecting Rule,2012 HOW TO PASS values rules.data.head in this case . There are two input fields here???</p>
<div class="col-md-4">
<div class="form-group label-floating">
<label class="control-label">Item</label>
<input type="text" class="form-control" v-model="bok.data[0].head" required="">
</div>
</div>
<div class="col-md-4">
<div class="form-group label-floating">
<label class="control-label">Quantity Seized</label>
<input type="text" class="form-control" v-model="bok.data[0].head" required="">
</div>
</div>
</div>
<div class="row" v-if="bok.name == 'Act,1961'">
<p>When selecting Act,1931 Its a select option, I need to select multiple options from here and pass values as rules.data.head. //After I select multiple options I have input fields corresponding to the options. This to be send as rules.data.value.. How
to do this?</p>
<div class="col-md-4">
<div class="form-group label-floating">
<label class="control-label">Select</label>
<select class=" form-control" v-model="bok.data[0].head" multiple="">
<option value="1">life</option>
<option value="2">Enment</option>
</select>
</div>
</div>
</div>
<div class="row" v-if="bok.data[0].head == 1">
<p>If option is 1, i should display this and pass value as rules.data.value . HERE THERE ARE TWO INPUT FIELDS How to pass the values</p>
<div class="col-md-4">
<div class="form-group label-floating">
<label class="control-label">Area1</label>
<input type="text" class="form-control" required="" v-model="bok.data[0].value">
</div>
</div>
<div class="col-md-4">
<div class="form-group label-floating">
<label class="control-label">Area2</label>
<input type="text" class="form-control" required="" v-model="bok.data[0].value">
</div>
</div>
</div>
<div class="row" v-if="bok.data[0].head == 2">
<div class="col-md-4">
<div class="form-group label-floating">
<label class="control-label">No.</label>
<input type="text" class="form-control" required="" v-model="bok.data[0].value">
</div>
</div>
<div class="col-md-4">
<div class="form-group label-floating">
<label class="control-label">Model</label>
<input type="text" class="form-control" required="">
</div>
</div>
</div>
</div>
<a #click="addNewRules">Add Another Rule</a>
</div>
My approach is basically change the type of the data[0].head and data[0].value depending on the options you selected.
So for example, if you select Rule,2012, then data[0].head would be an object with item and qty as its items. And if you select Act,1961, data[0].head would be an array of numbers (e.g. ['1', '2']) and data[0].value would be an object with area_1 and area_2 or number and model or all the four items.
See and try the code snippet to see the code I added/changed.
(Or compare your code with mine and you'd see the changes.)
addForm = new Vue({
el: "#addForm",
data: {
rules: [{
name: null,
section: null,
data: [{
head: null,
value: null
}]
}],
},
methods: {
addNewRules: function() {
this.rules.push({
name: null,
section: null,
data: [{
head: null,
value: null
}]
});
},
removeRuleDataValueProps: function(i) {
var d = this.rules[i].data[0];
if (jQuery.inArray('1', d.head) < 0) {
Vue.delete(d.value, 'area_1');
Vue.delete(d.value, 'area_2');
}
if (jQuery.inArray('2', d.head) < 0) {
Vue.delete(d.value, 'number');
Vue.delete(d.value, 'model');
}
},
_setRuleDataHeadDataType: function(i) {
var d = this.rules[i].data[0],
h = d.head,
_h = d._head,
_restore = true;
if (undefined === _h) {
d._head = h;
_restore = false;
}
switch (this.rules[i].name) {
case 'Rule,2012':
var a = Array.isArray(h);
if (a || null === h || 'object' !== typeof h) {
Vue.set(d, 'head', {});
}
break;
case 'Act,1961':
if (!Array.isArray(h)) {
Vue.set(d, 'head', []);
}
break;
default:
if (_restore && undefined !== _h) {
d.head = _h;
}
break;
}
},
_setRuleDataValueDataType: function(i) {
var d = this.rules[i].data[0],
v = d.value,
_v = d._value,
_restore = true;
if (undefined === _v) {
d._value = v;
_restore = false;
}
switch (this.rules[i].name) {
case 'Act,1972':
case 'Act,1961':
var a = Array.isArray(v);
if (a || null === v || 'object' !== typeof v) {
Vue.set(d, 'value', {});
}
if (_restore) {
this.removeRuleDataValueProps(i);
}
break;
default:
if (_restore && undefined !== _v) {
d.value = _v;
}
break;
}
},
setRuleDataType: function(i, k) {
if (this.rules[i] && this.rules[i].data[0]) {
if (!k || 'head' === k) {
this._setRuleDataHeadDataType(i);
}
if (!k || 'value' === k) {
this._setRuleDataValueDataType(i);
}
}
}
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.min.js"></script>
<div id="addForm">
<h3>Try the different options and see the JSON output changes.</h3>
<div class="card-content" v-for="(bok, index) in rules" :key="index">
<p>This is the first part which is fine for me</p>
<div class="row">
<div class="col-md-6">
<div class="form-group label-floating">
<label class="control-label">Act</label>
<!-- Here we change the type of `bok.data[0].head` depending on the selected option. -->
<select class="form-control" v-model="bok.name" #change="setRuleDataType(index)">
<option value="Act,1972">Act,1972</option>
<option value="Rule,2012">Rule,2012(CEMR)</option>
<option value="Act,1961">Act,1961</option>
</select>
</div>
</div>
<!--</div>-->
<div class="col-md-6">
<div class="form-group label-floating">
<label class="control-label">Section</label>
<input type="text" class="form-control" v-model="bok.section">
</div>
</div>
<!-- Here, `bok.data[0].head` is expected to be a `string`. -->
<div class="row" v-if="bok.name == 'Act,1972'">
<p>When selecting Act,1972 is here rules.data.head. Fine for me</p>
<div class="col-md-4">
<div class="form-group label-floating">
<label class="control-label">Arms</label>
<input type="text" class="form-control" v-model="bok.data[0].head" #change="setRuleDataType(index, 'value')" required="">
</div>
</div>
</div>
<!-- Here, `bok.data[0].head` is an `object` with 'item' and 'qty'. -->
<div class="row" v-if="bok.name == 'Rule,2012'">
<p>When Selecting Rule,2012 HOW TO PASS values rules.data.head in this case . There are two input fields here???</p>
<div class="col-md-4">
<div class="form-group label-floating">
<label class="control-label">Item</label>
<input type="text" class="form-control" v-model="bok.data[0].head.item" required="">
</div>
</div>
<div class="col-md-4">
<div class="form-group label-floating">
<label class="control-label">Quantity Seized</label>
<input type="text" class="form-control" v-model="bok.data[0].head.qty" required="">
</div>
</div>
</div>
<!-- Here, `bok.data[0].head` would be an array of numbers. -->
<div class="row" v-if="bok.name == 'Act,1961'">
<p>When selecting Act,1931 Its a select option, I need to select multiple options from here and pass values as rules.data.head. //After I select multiple options I have input fields corresponding to the options. This to be send as rules.data.value.. How
to do this?</p>
<div class="col-md-4">
<div class="form-group label-floating">
<label class="control-label">Select</label>
<select class=" form-control" v-model="bok.data[0].head" #change="removeRuleDataValueProps(index)" multiple="">
<option value="1">life</option>
<option value="2">Enment</option>
</select>
</div>
</div>
</div>
<div class="row" v-if="jQuery.inArray('1', bok.data[0].head) > -1">
<p>If option is 1, i should display this and pass value as rules.data.value . HERE THERE ARE TWO INPUT FIELDS How to pass the values</p>
<div class="col-md-4">
<div class="form-group label-floating">
<label class="control-label">Area1</label>
<input type="text" class="form-control" required="" v-model="bok.data[0].value.area_1">
</div>
</div>
<div class="col-md-4">
<div class="form-group label-floating">
<label class="control-label">Area2</label>
<input type="text" class="form-control" required="" v-model="bok.data[0].value.area_2">
</div>
</div>
</div>
<div class="row" v-if="jQuery.inArray('2', bok.data[0].head) > -1">
<div class="col-md-4">
<div class="form-group label-floating">
<label class="control-label">No.</label>
<input type="text" class="form-control" required="" v-model="bok.data[0].value.number">
</div>
</div>
<div class="col-md-4">
<div class="form-group label-floating">
<label class="control-label">Model</label>
<input type="text" class="form-control" required="" v-model="bok.data[0].value.model">
</div>
</div>
</div>
<h3>The JSON value of <code>bok</code></h3>
<textarea rows="3" cols="75%" readonly>{{ JSON.stringify(bok) }}</textarea>
</div>
<a #click="addNewRules">Add Another Rule</a>
</div>
My opinion,
Based on the HTML you provied, create one data property=ruleTemplate (it makes sure v-model with related form controls).
When add new rules, push one clone of the template to the rules
When you need the data, just convert the rules to the specific format like
this.getFormattedRules in below demo.
Below is the demo:
addForm = new Vue({
el: "#addForm",
data: {
ruleTemplates: {
name: '',
section: '',
subMenu: {
'Act,1972': '',
'Rule,2012': {'item': '','qty': ''},
'Act,1961': {'head':[], options:{'option1':'', 'option2':''}}
}
},
rules: [{
name: '',
section: '',
subMenu: {
'Act,1972': '',
'Rule,2012': {'item': '','qty': ''},
'Act,1961': {'head':[], options:{'option1':'', 'option2':''}}
}
}
],
},
computed: {
formatedJson: function () {
let handler1972 = function (data) {
return [{'head': 'Arms', 'value': data}]
}
let handler2012 = function (data) {
return [{'head': 'item', 'value': data.item},{'head': 'qty', 'value': data.qty}]
}
let handler1961 = function (data) {
return [{'head': 'option1', 'value': data.options.option1},{'head': 'option1', 'value': data.options.option2}]
}
let handlers = {'Act,1972': handler1972, 'Rule,2012': handler2012, 'Act,1961': handler1961
}
return this.rules.map((rule) => {
let formatedRule = new Object()
// convert the rule to the specific format
formatedRule.name = rule.name
formatedRule.section = rule.section
handler = handlers[rule.name]
formatedRule.data = handler ? handler(rule.subMenu[rule.name]) : []
return formatedRule
})
}
},
methods: {
addNewRules: function() {
this.rules.push(Object.assign({},this.ruleTemplates))
}
}
})
.show-format {
position:absolute;
top:2px;
right -4px;
background-color:gray
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.min.js"></script>
<div id="addForm">
<div class="show-format">Format: {{formatedJson}}</div>
<div class="card-content" v-for="(bok, index) in rules" :key="index">
<p>This is the first part which is fine for me</p>
<div class="row">
<div class="col-md-6">
<div class="form-group label-floating">
<label class="control-label">Act</label>
<select class="form-control" v-model="bok.name">
<option value="Act,1972">Act,1972</option>
<option value="Rule,2012">Rule,2012(CEMR)</option>
<option value="Act,1961">Act,1961</option>
</select>
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group label-floating">
<label class="control-label">Section</label>
<input type="text" class="form-control" v-model="bok.section">
</div>
</div>
<div class="row" v-if="bok.name == 'Act,1972'">
<p>When selecting Act,1972 is here rules.data.head. Fine for me</p>
<div class="col-md-4">
<div class="form-group label-floating">
<label class="control-label">Arms</label>
<input type="text" class="form-control" v-model="bok.subMenu['Act,1972']" required="">
</div>
</div>
</div>
<div class="row" v-if="bok.name == 'Rule,2012'">
<p>When Selecting Rule,2012 HOW TO PASS values rules.data.head in this case . There are two input fields here???</p>
<div class="col-md-4">
<div class="form-group label-floating">
<label class="control-label">Item</label>
<input type="text" class="form-control" v-model="bok.subMenu['Rule,2012']['item']" required="">
</div>
</div>
<div class="col-md-4">
<div class="form-group label-floating">
<label class="control-label">Quantity Seized</label>
<input type="text" class="form-control" v-model="bok.subMenu['Rule,2012']['qty']" required="">
</div>
</div>
</div>
<div class="row" v-if="bok.name == 'Act,1961'">
<p>When selecting Act,1931 Its a select option, I need to select multiple options from here and pass values as rules.data.head. //After I select multiple options I have input fields corresponding to the options. This to be send as rules.data.value.. How
to do this?</p>
<div class="col-md-4">
<div class="form-group label-floating">
<label class="control-label">Select</label>
<select class=" form-control" v-model="bok.subMenu['Act,1961'].head" >
<option value="1">life</option>
<option value="2">Enment</option>
</select>
</div>
</div>
</div>
<div class="row" v-if="bok.subMenu['Act,1961'].head == 1">
<p>If option is 1, i should display this and pass value as rules.data.value . HERE THERE ARE TWO INPUT FIELDS How to pass the values</p>
<div class="col-md-4">
<div class="form-group label-floating">
<label class="control-label">Area1</label>
<input type="text" class="form-control" required="" v-model="bok.subMenu['Act,1961'].options.option1">
</div>
</div>
<div class="col-md-4">
<div class="form-group label-floating">
<label class="control-label">Area2</label>
<input type="text" class="form-control" required="" v-model="bok.subMenu['Act,1961'].options.option2">
</div>
</div>
</div>
<div class="row" v-if="bok.subMenu['Act,1961'].head == 2">
<div class="col-md-4">
<div class="form-group label-floating">
<label class="control-label">No.</label>
<input type="text" class="form-control" required="" v-model="bok.subMenu['Act,1961'].options.option1">
</div>
</div>
<div class="col-md-4">
<div class="form-group label-floating">
<label class="control-label">Model</label>
<input type="text" class="form-control" required="" v-model="bok.subMenu['Act,1961'].options.option2">
</div>
</div>
</div>
</div>
<a #click="addNewRules" style="background-color:green">Add Another Rule</a>
</div>
hey why don't you go with multi-select checkbox drop-down and apply v-model on checkbox. ?
Link: How to use Checkbox inside Select Option

bootstrap validator submit handle

I am using bootstrap validator to validate my form created with bootstrap.
I have used the bootstrapValidator function to validate my form and also built in submitHandle of this function. In submitHandle, i am using simply post method as you can see.
major problem is I am not able to submit my form after clicking the submit button.You can also run code snippet and can see that after hitting submit button,it just stuck and then if I change any of the above field and then click submit again then it works fine. Not able to make it work on first attempt.
Not able to find bug....any help would be appreciated.
thanks!!
$(document).ready(
function() {
var validator = $("#registration-form").bootstrapValidator({
live: 'enabled',
feedbackIcons: {
//valid: 'glyphicon glyphicon-ok',
//invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: {
fname: {
message: "this field is required",
validators: {
notEmpty: {
message: "this field is required"
},
stringLength: {
max: 20,
message: "this field cannot be larger than 20 characters"
}
}
},
lname: {
message: "This field is required",
validators: {
notEmpty: {
message: "this field is required"
},
stringLength: {
max: 20,
message: "this field cannot be larger than 20 characters"
}
}
},
department: {
validators: {
greaterThan: {
value: 1,
message: "choose one department"
}
}
},
year: {
validators: {
greaterThan: {
value: 1,
message: "select your current year"
}
}
},
email: {
message: "Email address is required",
validators: {
notEmpty: {
message: "Please provide an email address"
},
emailAddress: {
message: "invalid email address"
}
}
}
},
submitHandler: function(validator, form, submitButton) {
$.ajax({
url: 'register.php',
type: 'post',
dataType: 'json',
data: $("#registration-form").serialize(),
success: function(data) {;
}
});
}
});
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Learning Boostrap</title>
<!-- Bootstrap CSS -->
<link href="css/bootstrap.min.css" rel="stylesheet" />
<link href="css/basic-template.css" rel="stylesheet" />
<link href="css/style.css" rel="stylesheet" />
<!-- BootstrapValidator CSS -->
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-validator/0.5.3/css/bootstrapValidator.min.css" rel="stylesheet" />
<!-- jQuery and Bootstrap JS -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-rc1/jquery.min.js" type="text/javascript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha/js/bootstrap.min.js" type="text/javascript"></script>
<!-- BootstrapValidator -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.bootstrapvalidator/0.5.3/js/bootstrapValidator.min.js" type="text/javascript"></script>
</head>
<body>
<div class="row">
<div class="column col-md-6">
<div class="panel panel-default panel_custom">
<div class="panel-heading" style="background:linear-gradient(to left,black 70%,#300032); border:0px">Registration</div>
<div class="panel-body">
<form id="registration-form" method="POST" action="register.php" role="form">
<div class="form-group">
<label class="control-label" for="fname">name:</label>
<div class="row">
<div class="column col-md-6">
<input type="text" class="form-control" id="fname" name="fname" placeholder="First" />
</div>
<div class=" col-md-6">
<input type="text" class="form-control" id="lname" name="lname" placeholder="Last" />
</div>
</div>
</div>
<div class="row">
<div class="column col-md-6">
<div class="form-group">
<label class="control-label" for="department" style="padding-top:10px">Department:</label>
<Select id="department" name="department" class="form-control" ">
<option value="0 ">choose one</option>
<option value="1 ">computer Science</option>
<option value="2 ">Bio medical science</option>
<option value="3 ">Instrumentaion</option>
<option value="4 ">Physics</option>
<option value="5 ">Polymer science</option>
<option value="6 ">Microbiology</option>
<option value="7 ">Food technology</option>
<option value="8 ">Electronics</option>
</select>
</div>
</div>
<div class="form-group ">
<div class="column col-md-6 " >
<label class="control-label " for="year " style="padding-top:10px ">Year:</label>
<Select id="year " name="year " class="form-control " ">
<option value="0">choose year</option>
<option value="1">1st</option>
<option value="2">2nd</option>
<option value="3">3rd</option>
<option value="4">4th</option>
</select>
</div>
</div>
</div>
<div class="row">
<div class="column col-md-6">
<div class="form-group">
<label class="control-label" for="male" style="padding-top:10px">Gender:</label>
<div class="radio">
<label>
<input type="radio" value="1" name="gender" required/>Male</label>
</div>
<div class="radio">
<label style="padding-left:20px">
<input type="radio" value="2" name="gender" />Female</label>
</div>
</div>
</div>
<div class="column col-md-6">
<div class="form-group">
<label class="control-label" for="email" style="padding-top:10px">E-mail Address:</label>
<input type="text" class="form-control" id="email" placeholder="Email Address" name="email" />
</div>
</div>
</div>
<div class="row">
<div class="column col-md-12">
<button class="btn btn-success" type="submit" value="but" name="submit">Submit</button>
</div>
</div>
</form>
<div id="confirmation" class="alert alert-success hidden" style="background:linear-gradient(to left,black 70%,#300032); border:none;">
<span class="glyphicon glyphicon-star"></span>
<h4>Thank you for registering. We will revert back shortly on email provided by you</h4>
</div>
</div>
</div>
</div>
</body>
</html>

Based on selected option on one page hide input on another page in mvc

Hi i have this view Index :
<h1>Přidání nové reklamy do systému</h1>
<div class="row">
<div class="col-md-12">
<div class="row">
#using (Html.BeginForm("Index", "Home", FormMethod.Post, new { #area = "Home", #role = "form" }))
{
<!-- Select Basic -->
<div class="form-group">
<label class="col-md-4 control-label" for="typ_reklamy">Typ reklamy</label>
<div class="col-md-8">
<select id="fnivel" name="typ_reklamy" class="form-control">
<option value="1">Reklama na určitou částku</option>
<option value="2">Reklama na určitou dobu</option>
<option style="display:none;" value="3">Reklama na určitý počet kliknutí</option>
</select>
</div>
</div>
}
</div>
</div>
</div>
And when i select this option in selecet:
<option value="1">Reklama na určitou částku</option>
I need on this page :
<h1>Přidání nové reklamy do systému</h1>
<div class="row">
<div class="col-md-12">
<div class="row">
#using (Html.BeginForm("Detail", "Home", FormMethod.Post, new { #area = "Home", #role = "form" }))
{
<fieldset>
<div class="form-group" id="fnivel2" style="margin-bottom:10px;">
<label class="col-md-3 control-label" for="datumz">Datum začátku</label>
<div class="col-md-7">
<div class="editor-field">
<input id="textinput" readonly name="datumz" type="text" value="#Model.allAdvert.datumz" class="form-control input-md" />
</div>
</div>
</div>
<div class="form-group" id="fnivel3" style="margin-bottom:10px;">
<label class="col-md-3 control-label" for="datumk">Datum konce</label>
<div class="col-md-7">
<div class="editor-field">
<input id="textinput" readonly name="datumk" type="text" value="#Model.allAdvert.datumk" class="form-control input-md" />
</div>
</div>
</div>
</fieldset>
}
</div>
</div>
</div>
Hide this two inputs:
<div class="form-group" id="fnivel2" style="margin-bottom:10px;">
<label class="col-md-3 control-label" for="datumz">Datum začátku</label>
<div class="col-md-7">
<div class="editor-field">
<input id="textinput" readonly name="datumz" type="text" value="#Model.allAdvert.datumz" class="form-control input-md" />
</div>
</div>
</div>
<div class="form-group" id="fnivel3" style="margin-bottom:10px;">
<label class="col-md-3 control-label" for="datumk">Datum konce</label>
<div class="col-md-7">
<div class="editor-field">
<input id="textinput" readonly name="datumk" type="text" value="#Model.allAdvert.datumk" class="form-control input-md" />
</div>
</div>
But i don´t know how to accomplish this in mvc.
Problem is how to pass value of option from view index to view detail.
Please can you help me ?
Use onchange="postvalues()" event and post values and catch in action
JavaScript function
function postvalues()
{
$.ajax({ url: '/home/Detail',
type: 'POST',
data: { optionvalue: $("#fnivel").val() },
dataType: 'json',
success: success
});
}
In controller
[HttpPost]
public ActionResult Detail(string optionvalue)
{
ViewBag.Optionvalue=optionvalue
return View();
}

how to validate input elements with the same name with jquery validate plugin

I have a list of text inputs in a form with the same name, as in an array of input elements. how can i use jquery validation plugin to validate each of these input elements. below is a snippet of what if what I have done so far.
HTML
<?php echo form_open('setup/new_session_validate/'.$school->university_alias, 'class="cmxform form-horizontal tasi-form" id="school_form" method="post"') ?>
<div class="form-group">
<label for="session_name" class="col-sm-2 control-label">Session title</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="session_name" name="session_name" />
</div>
</div>
<div class="form-group">
<label for="session_start_date" class="col-sm- col-sm-2 control-label">Start date for session</label>
<div class="col-sm-4">
<input type="text" class="form-control" id="session_start_date" name="session_start_date" />
</div>
<label for="session_end_date" class="col-sm-4 col-sm-2 control-label">End date for session</label>
<div class="col-sm-4">
<input type="text" class="form-control" id="session_end_date" name="session_end_date" />
</div>
</div>
<header class="panel-heading grey">
Semester 1
</header>
<div class="panel-body" style="border-bottom:1px solid #eee; padding:2% 0% 2% 0%">
<div class="form-group">
<label for="semester_1_start" class="col-sm-2 control-label">Start date</label>
<div class="col-sm-4">
<input type="text" class="form-control semester_start_dates" id="semester_1_start" src="1" name="semester_start_dates[]" />
</div>
<label for="semester_1_end" class="col-sm-2 control-label">End date</label>
<div class="col-sm-4">
<input type="text" class="form-control semester_end_dates" id="semester_1_end" src="1" name="semester_end_dates[]" />
</div>
</div>
</div>
<header class="panel-heading grey">
Semester 2
</header>
<div class="panel-body" style="border-bottom:1px solid #eee; padding:2% 0% 2% 0%">
<div class="form-group" style="">
<label for="semester_2_start" class="col-sm-2 control-label">Start date</label>
<div class="col-sm-4">
<input type="text" class="form-control semester_start_dates" id="semester_2_start" src="2" name="semester_start_dates[]" />
</div>
<label for="semester_2_end" class="col-sm-2 control-label">End date</label>
<div class="col-sm-4">
<input type="text" class="form-control semester_end_dates" id="semester_2_end" src="2" name="semester_end_dates[]" />
</div>
</div>
</div>
<div class="panel-body" style="">
<div class="form-group">
<div class="col-sm-1">
<button type="button" class="btn btn-danger close_session_form">Cancel</button>
</div>
<div class="col-sm-1 pull-right">
<button type="submit" class="btn btn-primary" id="submit">Submit</button>
</div>
</div>
</div>
javascript
$.validator.setDefaults({
submitHandler: function(form){
form.submit();
},
ignore: [],
});
// validate school form on submit
$('#submit').click(function(){
$("#school_form").validate({
rules: {
session_name: "required",
session_start_date: "required",
session_end_date: "required",
},
messages: {
session_name: "Please enter an identification for the session",
session_start_date: "Please enter a start date for the session",
session_end_date: "Please enter a end date for the session",
}
});
var i = 1;
$(".semester_start_dates").each(function(){
$("#semester_"+i+"_start").rules("add", {
required: true,
messages: {
required: "Please enter a start date for semester "+i+" of the session"
}
});
$("#school_form").validate().element("#semester_"+i+"_start");
i++;
});
var j = 1;
$(".semester_end_dates").each(function(){
$("#semester_"+j+"_end").rules("add", {
required: true,
messages: {
required: "Please enter an end date for semester "+j+" of the session"
}
});
$("#school_form").validate().element("#semester_"+j+"_end");
j++;
});
});
Note it tries to validate the elements but error message placement malfunctions.

Categories