bootstrap form validation only one field required - javascript

I have a form that has userID and screen name input fields.
When validating I need to make sure that at least one of them is entered (if both were entered I only take one). The html:
this.addFormValidators = function () {
$('#editCreatePipeForm').formValidation({
framework: 'bootstrap',
icon: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: {
ConsumerKey: {
validators: {
notEmpty: {
message: 'The Consumer Key is required'
}
}
},
ConsumerKeySecret: {
validators: {
notEmpty: {
message: 'The Consumer Key Secret is required'
}
}
},
CollectionIntervalSec: {
validators: {
notEmpty: {
message: 'The collection interval is required'
},
between: {
message: 'The collection interval must be a number greater than 10',
min: 10,
max: 1000000000
}
}
},
//KeepHistoricalDataTimeSec: {
// validators: {
// notEmpty: {
// message: 'The retain data value is required'
// },
// between: {
// message: 'The retain data value must be a number greater than 1000',
// min: 1000,
// max: 1000000000
// }
// }
//},
Description: {
validators: {
stringLength: {
max: 500,
message: 'The description must be less than 500 characters long'
}
}
}
}
}, null);
};
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="ScreenName" class="col-md-4 YcdFormLabel" title="screen name of user to retrieve">Screen name</label>
<div class="col-md-8">
<input type="text" placeholder="Screen Name" class="form-control user" autocomplete="off"
name="screenName"
id="screenName" data-bind="value: screenName, valueUpdate: 'keyup'"/>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-4"/>
<div class="col-md-6">
<div class="form-group">
#*<div class="col-md-8">*#
<label for="or" class="col-md-10">or</label>
#*</div>*#
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="userID" class="col-md-4 YcdFormLabel" title="user_ID of user to retrieve">User ID</label>
<div class="col-md-8">
<input type="text" placeholder="User ID" class="form-control user" autocomplete="off"
name="userID"
id="userID" data-bind="value: userID, valueUpdate: 'keyup'"/>
</div>
</div>
</div>
</div>

I added another function which I called it before submitting instead of using Bootstrap and jQuery form validation.
private hasTimelineAndUsername = (): boolean => {
if (this.viewModel.searchSelection() == "timeline"
&& ((this.viewModel.userID() == "" ||
this.viewModel.userID() == null) &&
(this.viewModel.screenName() == "" ||
this.viewModel.screenName() == null))) {
return false
}
return true;
}
The submitting function:
public getCollectionParameters() {
var fv = $('#editCreatePipeForm').data('formValidation')
fv.validate();
var isValid = fv.isValid();
if (!isValid) {
toastr.error("Please fix all problems before saving");
return null;
}
if (!this.hasTimelineAndUsername()) {
toastr.clear();
toastr.error("Please type username/userID");
return null;
}
if (!this.validateData()) {
return null;
}
return JSON.stringify(ko.mapping.toJS(this.viewModel));
}

I hope my code will help you.
JSFiddle: https://jsfiddle.net/aice09/3wjdvf30/
CodePen: https://codepen.io/aice09/pen/XgQyem
GitHub: https://github.com/Ailyn09/project102/blob/master/chooseintwoinput.html
function verify() {
var screenName = document.getElementById("screenName").value;
var userID = document.getElementById("userID").value;
if (userID === '' && screenName === '') {
alert('Add value to any field');
}
if (userID !== '' && screenName === '') {
alert('Your screen name are currently empty. The value you will be taken is your screen name');
document.getElementById("takedvalue").value = userID;
}
if (userID === '' && screenName !== '') {
alert('Your user id are currently empty. The value you will be taken is your user identification');
document.getElementById("takedvalue").value = screenName;
}
if (userID !== '' && screenName !== '') {
document.getElementById("mainbtn").style.display = "none";
document.getElementById("backbtn").style.display = "initial";
document.getElementById("choosescreenName").style.display = "initial";
document.getElementById("chooseuserID").style.display = "initial";
}
}
//Reset Form
$('.backbtn').click(function () {
document.getElementById("mainbtn").style.display = "initial";
document.getElementById("backbtn").style.display = "none";
document.getElementById("choosescreenName").style.display = "none";
document.getElementById("chooseuserID").style.display = "none";
});
//Choose First Input
$('.choosescreenName').click(function () {
var screenName = document.getElementById("screenName").value;
document.getElementById("takedvalue").value = screenName;
});
//Choose Second Input
$('.chooseuserID').click(function () {
var userID = document.getElementById("userID").value;
document.getElementById("takedvalue").value = userID;
});
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://code.jquery.com/jquery-1.12.3.min.js"></script>
<div class="container">
<form action="POST">
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label for="screenName">Screen name</label>
<input type="text" placeholder="Screen Name" class="form-control " autocomplete="off" name="screenName" id="screenName" />
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label for="userID">User ID</label>
<input type="text" placeholder="User ID" class="form-control user" autocomplete="off" name="userID" id="userID" />
</div>
</div>
<div class="col-md-12">
<button type="button" class="btn btn-primary" id="mainbtn" onclick="verify();">SUBMIT</button>
<button type="reset" class="btn btn-primary backbtn" id="backbtn" style="display:none;">BACK</button>
<button type="button" class="btn btn-primary choosescreenName" id="choosescreenName" style="display:none;">CHOOSE SCREEN NAME</button>
<button type="button" class="btn btn-primary chooseuserID" id="chooseuserID" style="display:none;">CHOOSE USER ID</button>
</div>
<div class="col-md-12">
<hr>
<div class="form-group">
<label for="userID">Value</label>
<input type="text" placeholder="Taken Value" class="form-control" id="takedvalue" readonly />
</div>
</div>
</div>
</form>
</div>

Related

when i save to my database i don't receive my data

when i input data in the form to get Smtp, according to my code am to get the data and save it to my database but its not working, i don't receive any data info in my mongodb, i only get the Date
this is what my database looks like
my view(ejs)
<h1 class="mt-4">Dashboard</h1>
<div class="row mt-5">
<div class="col-md-6 m-auto">
<div class="card card-body">
<h1 class="text-center mb-3">
<i class="fas fa-user-plus"></i> Add Smtp
</h1>
<% include ./partials/messages %>
<form action="/users/mail" method="POST">
<div class="form-group">
<label for="smtpUsername">smtpUsername</label>
<input
type="name"
id="smtpUsername"
name="smtpUsername"
class="form-control"
placeholder="Enter smtpUsername"
value="<%= typeof smtpUsername != 'undefined' ? smtpUsername : '' %>"
/>
</div>
<div class="form-group">
<label for="smtpPassword">smtpPassword</label>
<input
type="name"
id="smtpPassword"
name="smtpPassword"
class="form-control"
placeholder="Enter smtpPassword"
value="<%= typeof smtpPassword != 'undefined' ? smtpPassword : '' %>"
/>
</div>
<div class="form-group">
<label for="smtpUrl">smtpUrl</label>
<input
type="name"
id="smtpUrl"
name="smtpUrl"
class="form-control"
placeholder="Enter smtpUrl"
value="<%= typeof smtpUrl != 'undefined' ? smtpUrl : '' %>"
/>
</div>
<button type="submit" class="btn btn-primary btn-block">
Add Smtp
</button>
</form>
</div>
</div>
</div>
<div class="row mt-5">
<div class="col-md-6 m-auto">
<div class="card card-body">
<h1 class="text-center mb-3">
<i class="fas fa-user-plus"></i> send mail
</h1>
<% include ./partials/messages %>
<form action="/users/mail" method="POST">
<div class="form-group">
<label for="to">to</label>
<input
type="name"
id="to"
name="to"
class="form-control"
placeholder="Enter to"
value="<%= typeof to != 'undefined' ? to : '' %>"
/>
</div>
<div class="form-group">
<label for="bcc">bcc</label>
<input
type="name"
id="bcc"
name="bcc"
class="form-control"
placeholder="Enter bcc"
value="<%= typeof bcc != 'undefined' ? bcc : '' %>"
/>
</div>
<div class="form-group">
<label for="cc">cc</label>
<input
type="name"
id="cc"
name="name"
class="form-control"
placeholder="Enter cc"
value="<%= typeof cc != 'undefined' ? cc : '' %>"
/>
</div>
<div class="form-group">
<label for="subject">subject</label>
<input
type="name"
id="subject"
name="subject"
class="form-control"
placeholder="Enter subject"
value="<%= typeof subject != 'undefined' ? subject : '' %>"
/>
</div>
<div class="form-group">
<label for="message">message</label>
<input
type="name"
id="message"
name="message"
class="form-control"
placeholder="Enter message"
value="<%= typeof message != 'undefined' ? message : '' %>"
/>
</div>
<button type="submit" class="btn btn-primary btn-block">
Register
</button>
</form>
</div>
</div>
</div>
Logout
when i input data in the form to get Smtp, according to my code am to get the data and save it to my database but its not working, i don't receive any data info in my mongodb, i only get the Date
my schema
const mongoose = require('mongoose');
const MailSchema = new mongoose.Schema({
to: {
type: String,
},
cc: {
type: String,
},
bcc: {
type: String,
},
subject: {
type: String,
},
message: {
type: String,
},
attachment: {
type: String,
},
date: {
type: Date,
default: Date.now
},
});
const SmtpSchema = new mongoose.Schema({
smtpUrl: {
type: String,
required: true
},
smtpUsername: {
type: String,
required: true
},
smtpPassword: {
type: String,
required: true
},
date: {
type: Date,
default: Date.now
},
});
const Mail = mongoose.model('Mail', MailSchema);
const Smtp = mongoose.model('Smtp', SmtpSchema);
module.exports = Mail;
when i input data in the form to get Smtp, according to my code am to get the data and save it to my database but its not working, i don't receive any data info in my mongodb, i only get the Date
my Route
router.get('/mail', forwardAuthenticated, (req, res) =>
res.render('mail', {
user: req.user,
mail: req.mail
})
);
router.post('/mail', (req, res) => {
const { to, cc, bcc, subject, message, attachment } = req.body;
const { smtpUrl, smtpUsername, smtpPassword } = req.body;
console.log(smtpUrl)
console.log(smtpPassword)
console.log(smtpUsername)
let errors = [];
if (!smtpUrl || !smtpUsername || !smtpPassword) {
errors.push({ msg: 'Add an account' });
res.render('mail', {
smtpUrl,
smtpPassword,
smtpUsername
});
}else{
console.log(smtpUrl)
console.log(smtpPassword)
console.log(smtpUsername)
const newSmtp = new Smtp({
smtpUrl,
smtpPassword,
smtpUsername
});
newSmtp
.save()
.then(mail => {
req.flash(
'success_msg',
'Account Added'
);
})
.catch(err => console.log(err));
}
if (!to || !subject || !message) {
errors.push({ msg: 'Please enter all fields' });
}
if (errors.length > 0) {
res.render('mail', {
errors,
to,
cc,
bcc,
subject,
message,
attachment,
});
} else {
const newMail = new Mail({
to,
cc,
bcc,
subject,
message,
attachment,
});
let transporter = nodemailer.createTransport({
service: smtpUrl,
auth: {
user: smtpUsername,
pass: smtpPassword
}
});
let mailOptions = {
from: smtpUsername,
to: to,
subject: subject,
text: `${message}`
};
transporter.sendMail(mailOptions, function (error, info) {
if (error) {
console.log(error);
} else {
newMail
.save()
.then(mail => {
req.flash(
'success_msg',
'mail sent'
);
})
.catch(err => console.log(err));
console.log('Email sent: ' + info.response);
}
});
}
})

Vuelidate errors return true but elements don't render

I have a contact form that uses vuelidate to validate fields. The problem is - the validation works, but the errors don't render.
$v.name.dirty is TRUE and $v.name.required is FALSE.
Logging $v.name.dirty && !$v.name.required returns TRUE which is the same condition in the v-if directive but the error elements still don't show.
However, when .$touch() is called and $v.name.dirty becomes true and $v.name.required false, anything I type in the input fields will show the errors.
JS:
import translationsBus from "../../app/translations";
export default {
name: "contactForm",
beforeMount() {
this.$store.dispatch("updateTranslations", translationsBus.translations);
},
data: function () {
return {
name: '',
email: '',
subject: '',
message: ' ',
errors: [],
isSuccessful: ''
}
},
mounted() {
var my_axios = axios.create({
baseURL: '/'
});
Vue.prototype.$http = my_axios;
},
computed: {
isLogged: function () {
return isLoggedOn;
},
shouldShowSubjectOption: function () {
return showSubjectOption;
},
translations: function () {
return this.$store.state.translations.translations;
},
},
methods: {
onContactUsClick: function onContactUsClick() {
const _this = this;
this.$v.$touch();
if (!this.$v.$error) {
let model = {
senderName: _this.name,
senderEmail: _this.email,
subject: _this.subject,
message: _this.message
};
this.$http.post('/home/contactus', model)
.then(response => {
console.log(response);
_this.isSuccessful = response.data;
})
.catch(e => {
console.log(e);
});
}
}
},
validations: {
email: {
required: required,
isValidEmail: function isValidEmail(value) {
var re = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
return re.test(value);
}
},
name: {
required: required
},
subject: {
required: required
},
message: {
required: required
}
}
}```
HTML:
<div v-bind:class="{ 'col-lg-6' : shouldShowSubjectOption, 'col-lg-12' : !shouldShowSubjectOption }">
<div id="form-contact">
<h1 class="lead">Get in touch...</h1>
<form class="text-center" >
<div class="form-group">
<label for="name">{{translations['contact_Form_Name']}}</label>
<div class="input-group">
<span class="input-group-addon"><span class="fa fa-user"></span></span>
<input type="text" class="form-control" name="senderName" id="senderName" v-model:bind="name" v-bind:placeholder="translations['contact_Form_NamePlaceholder']" />
</div>
<div class="has-error" v-cloak>
<label class="control-label" v-if="$v.name.$dirty && !$v.name.required">{{translations['shared_Validation_ReuiredField']}}</label>
</div>
</div>
<div class="form-group">
<label for="email">{{translations['contact_Form_EmailAddress']}}</label>
<div class="input-group">
<span class="input-group-addon"><span class="fa fa-envelope"></span></span>
<input type="email" class="form-control" name="senderEmail" id="senderEmail" v-model:bind="email" v-bind:placeholder="translations['contact_Form_EmailAddressPlaceholder']" />
</div>
<div class="has-error" v-cloak>
<label class="control-label" v-if="$v.email.$dirty && !$v.email.required">{{translations['shared_Validation_ReuiredField']}}</label>
<label class="control-label" v-if="$v.email.$dirty && $v.email.required && !$v.email.isValidEmail">{{translations['contact_Form_EmailAddressValidationMessage']}}</label>
</div>
</div>
<div class="form-group" v-if="shouldShowSubjectOption">
<label for="subject">{{translations['contact_Form_Subject']}}</label>
<select id="subject" name="subject" class="form-control" v-model:bind="subject" v-bind:title="translations['contact_Form_SubjectPickerText']">
<option value="service">1</option>{{translations['contact_Form_SubjectOption_GCS']}}
<option value="suggestions">2</option>{{translations['contact_Form_SubjectOption_Suggestions']}}
<option value="product">3</option>{{translations['contact_Form_SubjectOption_ProductSupport']}}
</select>
</div>
<div class="has-error" v-cloak>
<label class="control-label" v-if="$v.subject.$dirty && !$v.subject.required" v-cloak>{{translations['shared_Validation_ReuiredField']}}</label>
</div>
<div class="form-group">
<label for="name">{{translations['contact_Form_Message']}}</label>
<textarea name="message" id="message" class="form-control" v-model:bind="message" rows="9" cols="25"
placeholder="">{{translations['contact_Form_Message']}}</textarea>
</div>
<div class="has-error" v-cloak>
<label class="control-label" v-if="$v.message.$dirty && !$v.message.required">{{translations['shared_Validation_ReuiredField']}}</label>
</div>
<div class="form-group" v-if="isLogged">
<div class="g-recaptcha" data-sitekey=""></div>
</div>
<button type="button" class="btn btn-primary btn-block" v-on:click="onContactUsClick" id="btnContactUs">{{translations['contact_Form_SendMessageButton']}}</button>
</form>
</div>
</div>
</div>
</div>
I expect error elements to appear on submit.

Salesforce form showing errors even when filled out correctly

I am new to salesforce and don't have a lot of experience with javascript. The issue I am having is that as I am testing a form and filling out the inputs it is adding the the "has-error" class to the parent div even when the input is filled out correctly. However, it will allow the form to be submitted so it is not conflicting with that.
I took over the work from another developer so Im not sure what is causing the error.
The is the javascript for the salesforce form. I am also using validate.js:
'use strict';
var constraints = {
// First Name
'00N4100000CJ8sT': {
presence: {
message: '^First Name is required'
},
length: {
maximum: 80
}
},
// Last Name
'00N4100000CJ8sY': {
presence: {
message: '^Last Name is required'
},
length: {
maximum: 80
}
},
// Appointment Date
'00N4100000EWaN0': {
presence: {
message: '^Date is not valid'
},
format: {
pattern: /^\d{1,2}\/\d{1,2}\/\d{4}$/,
},
},
// Patient Email
'00N4100000CJ8sE': {
presence: {
message: '^Email is required'
},
email: {
message: '^Email is not valid'
}
},
// Phone
'phone': {
presence: true,
format: {
pattern: /^[(]{0,1}[0-9]{3}[)]{0,1}[-\s\.]{0,1}[0-9]{3}[-\s\.]{0,1}[0-9]{4}$/,
message: '^Phone Number is not valid'
}
}
};
$('.salesforce-form').each(function () {
var form = this;
form.addEventListener('submit', function (ev) {
ev.preventDefault();
handleFormSubmit(form);
});
var inputs = document.querySelectorAll('input, textarea, select');
for (var i = 0; i < inputs.length; ++i) {
inputs.item(i).addEventListener('change', function (ev) {
var errors = validate(form, constraints) || {};
showErrorsForInput(this, errors[this.name]);
});
}
function handleFormSubmit(form, input) {
var errors = validate(form, constraints);
showErrors(form, errors || {});
if (!errors) {
showSuccess(form);
}
}
function showErrors(form, errors) {
_.each(form.querySelectorAll('input[name], select[name]'), function (input) {
showErrorsForInput(input, errors && errors[input.name]);
});
}
function showErrorsForInput(input, errors) {
var formGroup = closestParent(input, 'form-group');
var messages = formGroup.querySelector('.messages');
resetFormGroup(formGroup);
if (errors) {
formGroup.classList.add('has-error');
_.each(errors, function (error) {
addError(messages, error);
});
} else {
formGroup.classList.add('has-success');
}
}
function closestParent(child, className) {
if (!child || child == document) {
return null;
}
if (child.classList.contains(className)) {
return child;
} else {
return closestParent(child.parentNode, className);
}
}
function resetFormGroup(formGroup) {
formGroup.classList.remove('has-error');
formGroup.classList.remove('has-success');
_.each(formGroup.querySelectorAll('.help-block.error'), function (el) {
el.parentNode.removeChild(el);
});
}
function addError(messages, error) {
var block = document.createElement('p');
block.classList.add('help-block');
block.classList.add('error');
block.innerText = error;
messages.appendChild(block);
}
function showSuccess(form) {
var myEmail = form.querySelector('#my-email').value;
if (!myEmail.length > 0) {
form.querySelector('#orgid').value = '00D41000000MWct';
var postData = $(form).serializeArray();
$.ajax({
type: 'POST',
url: '(salesforce url goes here)',
data: postData,
success: function success(data, textStatus, jqXHR) {
//data: return data from server
},
error: function error(jqXHR, textStatus, errorThrown) {
//if fails
$(form).find('.form-group').fadeOut();
$('.thank-you-message').last().clone().appendTo(form).fadeIn();
dataLayer.push({
'event': 'gtm.formSubmit',
'gtm.elementClasses': form.className
});
}
});
}
}
});
This is the html for the salesforce form:
<form class="salesforce-form salesforce-contact-form" novalidate>
<div class="hide form-group">
<input id="my-email" name="my-email" type="text" />
<input type="hidden" id="orgid" name="orgid" />
<input type="hidden" id="email" name="email" value="test#email.com"/>
<input type="hidden" id="00N4100000IkI2v" name="00N4100000IkI2v" value="<?php echo get_permalink(); ?>" />
<input type="hidden" id="00N4100000IkHtO" name="00N4100000IkHtO" value="<?php echo get_client_ip(); ?>" />
<input type="hidden" id="00N4100000HxXj4" name="00N4100000HxXj4" value="New" />
<input type="hidden" id="00N4100000CL2tK" name="00N4100000CL2tK" value="Request Appointment" title="Form Type" />
</div>
<div class="col-md-6 col-sm-6 col-xs-6 form-group first-name">
<label for="00N4100000CJ8sT" class="hidden">First Name</label>
<input id="00N4100000CJ8sT" maxlength="80" name="00N4100000CJ8sT" size="20" type="text" placeholder="First Name: *">
<div class="messages"></div>
</div>
<div class="col-md-6 col-sm-6 col-xs-6 form-group last-name">
<label for="00N4100000CJ8sY" class="hidden">Last Name</label>
<input id="00N4100000CJ8sY" maxlength="80" name="00N4100000CJ8sY" size="20" type="text" placeholder="Last Name: *">
<div class="messages"></div>
</div>
<div class="col-md-6 col-sm-6 col-xs-6 form-group email">
<label for="00N4100000CJ8sE" class="hidden">Email</label>
<input id="00N4100000CJ8sE" maxlength="80" name="00N4100000CJ8sE" size="20" type="email" placeholder="Email: *">
<div class="messages"></div>
</div>
<div class="col-md-6 col-sm-6 col-xs-6 form-group phone">
<label for="phone" class="hidden">Phone</label>
<input id="phone" maxlength="40" name="phone" size="20" type="text" placeholder="Phone: *">
<div class="messages"></div>
</div>
<div class="col-md-12 col-xs-12 form-group appointment-date">
<label for="00N4100000EWaN0" class="hidden">Appointment Date</label>
<input id="00N4100000EWaN0" name="00N4100000EWaN0" size="20" type="text" placeholder="Appointment Date: *">
<div class="messages"></div>
</div>
<div class="col-md-12 col-sm-12 col-xs-12 form-group comments">
<label for="description" class="hidden">Comments</label>
<textarea id="description" name="description" placeholder="Comments:"></textarea>
</div>
<div class="col-md-12 col-sm-12 col-xs-12 form-group submit">
<input type="submit" value="Submit +" class="btn small"/>
</div>
</form>
Let me know if this needs more explanation or if you need to see any other files.

Get value from javascript

I have to get id from table data (SQL).
Below is a form, in which I have to get proper id. But in JavaScript I don't get id from more data. I am getting only same data id from table.
please tell me how to get id from table in SQL
HTML Form:
<div>
<textarea name="comment" id="comment1" class="form-control comment" rows="3" placeholder="Leave comment"></textarea>
<input type="hidden" id="cid1" value="<?php echo $ws1['forum_id']; ?>">
</div>
<input class="btn btn btn-noc" type="submit" value="Submit" id="addressSearch" href="#myModalnew" role="button" data-toggle="modal">
<form class="form-horizontal">
<div class="control-group">
<label class="control-label" for="inputEmail">User name</label>
<div class="controls">
<input type="text" id="username" placeholder="User name">
<p id="username_error" class="validation"></p>
</div>
</div>
<div class="control-group">
<label class="control-label" for="inputEmail">Email id</label>
<div class="controls">
<input type="text" id="email" placeholder="Email id">
<p id="email_error" class="validation"></p>
</div>
</div>
<div class="control-group">
<label class="control-label" for="inputEmail">Mobile no</label>
<div class="controls">
<input type="text" id="phone" placeholder="Mobile no">
<p id="phone_error" class="validation"></p>
</div>
</div>
<div class="control-group">
<div class="controls">
<input type="button" class="btn btn-nocone" value="Submit" onClick="xxx()">
</div>
</div>
</form>
Javascript:
function xxx() {
regexp=/^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
regexp1=/^\d{10}$/;
function showError(id, msg) {
if (msg != "") {
document.getElementById(id).innerHTML = '*' + msg;
}
else {
document.getElementById(id).innerHTML = msg;
}
}
err = '';
var username = document.getElementById("username").value;
if (username == "" || username == null) {
showError('username_error', 'Please Fill Name');
err = 1;
} else {
showError('username_error', '');
}
var email = document.getElementById("email").value;
if (!regexp.test(email)) {
showError('email_error', 'Please Fill valid Email address.');
err = 2;
} else {
showError('email_error', '');
}
var phone = document.getElementById("phone").value;
if (!regexp1.test(phone)) {
showError('phone_error', 'Please Fill valid Phone Number.');
err = 3;
} else {
showError('phone_error', '');
}
if(err!=''){
return false
}
else {
cmnt = document.getElementById('comment').value;
usr = document.getElementById('username').value;
emil = document.getElementById('email').value;
phn = document.getElementById('phone').value;
fid = document.getElementById('cid').value;
$.ajax({
type: "POST",
url:'submit_form/insert_comment.php',
dataType: "html",
cache: false,
async: false,
data: {
comment: cmnt,
username: usr,
email:emil,
phone:phn,
id: fid
}
});
}
showError('error','Your comment have been sent sucessfully');
$("#please").click();
}

knockout form validation message

I'd like to use Knockout.js to highlight errors on a form.
Currently i see all errors when i get the form,
I want to get them only if the user press on Save button.
So I'm try to set a flag that will be true only if the user press on it, and then to use it in all form but i don't have success with that.
I will apreciate some help with that. (or any other way to do it)
so i will need someting like that on my html:
<div class='liveExample' data-bind="css: {hideErrors: !hasBeenSubmittedOnce()">
and somewhere in my js file:
this.hasBeenSubmittedOnce = ko.observable(false);
this.save = function(){
this.hasBeenSubmittedOnce(true);
}
that my files
HTML
<div class='liveExample' data-bind="css: {hideErrors: !hasBeenSubmittedOnce()">
<form class="form-horizontal" role="form">
<div class="form-group">
<label class="col-sm-3 control-label">Store:</label>
<div class="col-sm-3" data-bind="css: { error: storeName.hasError() }">
<input data-bind='value: storeName, valueUpdate: "afterkeydown"' />
<span data-bind='text: storeName.validationMessage'> </span>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Company ID:</label>
<div class="col-sm-3" data-bind="css: { error: companyId.hasError }">
<input data-bind='value: companyId, valueUpdate: "afterkeydown"' />
<span data-bind='text: companyId.validationMessage'> </span>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Address</label>
<div class="col-sm-3" data-bind="css: { error: address.hasError }">
<input data-bind='value: address, valueUpdate: "afterkeydown"' />
<span data-bind='text: address.validationMessage'> </span>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Phone:</label>
<div class="col-sm-3" data-bind="css: { error: phone.hasError }">
<input data-bind='value: phone, valueUpdate: "afterkeydown"' />
<span data-bind='text: phone.validationMessage'> </span>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-3 col-sm-4">
<button class="btn btn-primary" data-bind="click: save">Add store</button>
</div>
</div>
</form>
Store:
Company ID:
Address
Phone:
Add store
</form>
js
define(['knockout'], function (ko){
ko.extenders.required = function(target, overrideMessage) {
//add some sub-observables to our observable
target.hasError = ko.observable();
target.validationMessage = ko.observable();
//define a function to do validation
function validate(newValue) {
target.hasError(newValue ? false : true);
target.validationMessage(newValue ? "" : overrideMessage || "This field is required");
}
validate(target());
target.subscribe(validate);
return target;
};
function AppViewModel(storeName, companyId, address, phone) {
this.storeName = ko.observable(storeName).extend({ required:"" });
this.companyId = ko.observable(companyId).extend({ required: "" });
this.address = ko.observable(address).extend({ required: "" });
this.phone = ko.observable(phone).extend({ required: ""});
this.hasError = ko.computed(function(){
return this.storeName.hasError() || this.companyId.hasError();
}, this);
this.hasBeenSubmittedOnce = ko.observable(false);
this.save = function(){
this.hasBeenSubmittedOnce(true);
}
}
return AppViewModel;
});
CSS file
.form-group span {
display: inherit;
}
.hideErrors .error span {
display: none;
}
I did some work around for this and not sure it is better way or not.
var showError=ko.observableArray([]);//it will store show Error Message
ko.extenders.required = function(target, overrideMessage) {
//add some sub-observables to our observable
target.hasError = ko.observable();
target.validationMessage = ko.observable();
//define a function to do validation
function validate(newValue) {
target.hasError($.trim(newValue) ? false : true);
target.validationMessage($.trim(newValue) ? "" : overrideMessage || "This field is required");
}
showError.push(function(){validate(target());});
target.subscribe(validate);
return target;
};
function AppViewModel(storeName, companyId, address, phone) {
this.storeName = ko.observable(storeName).extend({ required:"" });
this.companyId = ko.observable(companyId).extend({ required: "xcxcx" });
this.address = ko.observable(address).extend({ required: "" });
this.phone = ko.observable(phone).extend({ required: ""});
this.hasError = ko.computed(function(){
return self.storeName.hasError() || self.companyId.hasError();
}, this);
this.hasBeenSubmittedOnce = ko.observable(false);
this.save = function(){
ko.utils.arrayForEach(showError(),function(func){
func();
});
}
}
ko.applyBindings(new AppViewModel());
Fiddle Demo
You can use the visible knockout binding:
<div data-bind="visible: hasBeenSubmittedOnce">
As for the error class, you can use the define the default knockout validation class: 'validationElement' and call
ko.validation.init({ decorateElement: true});
Here you can find more:
https://github.com/Knockout-Contrib/Knockout-Validation/wiki/Configuration
(please note that decorateElement has been renamed 2013-11-21 to 'decorateInputElement')

Categories

Resources