I am fairly new to the MEAN Stack, and after following this tutorial : http://www.bradoncode.com/tutorials/mean-stack-tutorial-part-4-angularjs/, I was trying to make my own web application to send and receive invoices. I have a localhost:3000/invoices page set up which is currently empty ([ ]). I am trying to fill out a form and post to it localhost:3000/invoices so that the MongoDB database is populated. My MongoDB process is constantly running. This is the Model outlining all the fields I require in a record :
'use strict';
/**
* Module dependencies.
*/
var mongoose = require('mongoose'),
Schema = mongoose.Schema,
validation = require('./validation.server.model');
/**
* Invoices Schema
*/
var InvoiceSchema = new Schema({
invoice_date: {
type: Date,
default: Date.now
},
from_entity: {
type: String,
default: '',
trim: true,
required: 'legal entity cannot be blank'
},
from_service: {
type: String,
default: '',
trim: true,
required: 'service line cannot be blank'
},
country: {
type: String,
default: '',
trim: true,
required: 'country cannot be blank'
},
to_entity: {
type: String,
default: '',
trim: true,
required: 'legal entity cannot be blank'
},
to_service: {
type: String,
default: '',
trim: true,
required: 'service line cannot be blank'
},
partner: {
type: String,
default: '',
trim: true,
required: 'partner cannot be blank'
},
invoice_number: {
type: String,
default: '',
trim: true,
unique: true,
required: 'invoice number cannot be blank'
},
currency: {
type: String,
default: '',
trim: true,
required: 'currency cannot be blank'
},
amount: {
type: Number,
default: '',
trim: true,
required: 'amount cannot be blank'
}
});
mongoose.model('Invoice', InvoiceSchema);
This is my invoice client side controller :
'use strict';
// Invoices controller
angular.module('invoices').controller('InvoicesController', ['$scope', '$stateParams', '$location', 'Authentication', 'Invoices', '$filter',
function($scope, $stateParams, $location, Authentication, Invoices, $filter) {
$scope.authentication = Authentication;
$scope.currentPage = 1;
$scope.pageSize = 10;
$scope.offset = 0;
// Page changed handler
$scope.pageChanged = function() {
$scope.offset = ($scope.currentPage - 1) * $scope.pageSize;
};
// Create new Invoice
$scope.create = function() {
var invoice = new Invoices ({
amount: this.amount,
invoice_number: this.invoice_number,
partner: this.partner,
to_service: this.to_service,
to_entity: this.to_entity,
country: this.country,
from_service: this.from_service,
from_entity: this.from_entity
});
// Redirect after save
invoice.$save(function(response) {
$location.path('invoices/' + response._id);
// Clear form fields
$scope.name = '';
}, function(errorResponse) {
$scope.error = errorResponse.data.message;
});
};
// Remove existing Invoice
$scope.remove = function(invoice) {
if (invoice) {
invoice.$remove();
for (var i in $scope.invoices) {
if ($scope.invoices [i] === invoice) {
$scope.invoices.splice(i, 1);
}
}
} else {
$scope.invoice.$remove(function() {
$location.path('invoices');
});
}
};
// Update existing Invoice
$scope.update = function() {
var invoice = $scope.invoice;
invoice.$update(function() {
$location.path('invoices/' + invoice._id);
}, function(errorResponse) {
$scope.error = errorResponse.data.message;
});
};
// Find a list of Invoices
$scope.find = function() {
$scope.invoices = Invoices.query();
};
// Find existing Invoice
$scope.findOne = function() {
$scope.invoice = Invoices.get({
invoiceId: $stateParams.invoiceId
});
};
// Search for a Invoice
$scope.invoiceSearch = function(invoice) {
$location.path('invoices/' + invoice._id);
};
}
]);
And this is a simple form in AngularJS on the front-end :
<section data-ng-controller="InvoicesController">
<div class="page-header">
<h1>New Invoice</h1>
</div>
<div class="col-md-12">
<form class="form-horizontal" data-ng-submit="create()" novalidate>
<fieldset>
<div class="form-group">
<label class="control-label" for="invoice_number">Invoice Number</label>
<div class="controls">
<input type="text" data-ng-model="invoice.invoice_number" id="invoice_number" class="form-control" placeholder="Invoice Number" required>
</div>
</div>
<div class="form-group">
<label class="control-label" for="amount">Amount</label>
<div class="controls">
<input type="text" data-ng-model="invoice.amount" id="amount" class="form-control" placeholder="Amount" required>
</div>
</div>
<div class="form-group">
<label class="control-label" for="currency">Currency</label>
<div class="controls">
<input type="text" data-ng-model="invoice.currency" id="currency" class="form-control" placeholder="Currency" required>
</div>
</div>
<div class="form-group">
<label class="control-label" for="partner">Partner</label>
<div class="controls">
<input type="text" data-ng-model="invoice.partner" id="partner" class="form-control" placeholder="Partner" required>
</div>
</div>
<div class="form-group">
<label class="control-label" for="country">Country</label>
<div class="controls">
<input type="text" data-ng-model="invoice.country" id="name" class="form-control" placeholder="Country" required>
</div>
</div>
<div class="form-group">
<label class="control-label" for="to_service">Service Line (To:)</label>
<div class="controls">
<input type="text" data-ng-model="invoice.to_service" id="to_service" class="form-control" placeholder="Service Line (To:)" required>
</div>
</div>
<div class="form-group">
<label class="control-label" for="from_service">Service Line (From:)</label>
<div class="controls">
<input type="text" data-ng-model="invoice.from_service" id="from_service" class="form-control" placeholder="Service Line (From:)" required>
</div>
</div>
<div class="form-group">
<label class="control-label" for="to_entity">Entity(To:)</label>
<div class="controls">
<input type="text" data-ng-model="invoice.to_entity" id="to_entity" class="form-control" placeholder=" Entity (To:)" required>
</div>
</div>
<div class="form-group">
<label class="control-label" for="from_entity">Entity(From:)</label>
<div class="controls">
<input type="text" data-ng-model="invoice.from_entity" id="from_entity" class="form-control" placeholder=" Entity (From:)" required>
</div>
</div>
<div class="form-group">
<input type="submit" class="btn btn-default">
</div>
<div data-ng-show="error" class="text-danger">
<strong data-ng-bind="error"></strong>
</div>
</fieldset>
</form>
</div>
</section>
When I proceed and submit the form I get the following :
Amount is a required field as evident through the model, and I am always certain to fill in that value. I have typed numbers and decimals always, yet is says that field is required and displays Bad Request. Also whenever I do npm start, my application loads up without any errors. I have attempted watching several youtube tutorials, but none clarify the reason for this not working. Swift Help would be greatly appreciated :)
EDIT : When I remove the required from the Model, the transaction goes through, but none of the values inputted into the form are recorded, only the invoice date is.
You get a date because there is a default set for that. Define $scope.invoice = {} in your controller so that it is bound to your view (2-way). Then, change all fetches from $scope.invoice. For example:
$scope.invoice = {};
$scope.create = function() {
var invoice = new Invoices ({
amount: $scope.invoice.amount,
invoice_number: $scope.invoice.invoice_number,
partner: $scope.invoice.partner,
...
});
...
};
Related
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.
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>
I am trying to submit user details to a MailChimp list via PHP for multiple forms on the same page.
My code is as follows:
index.html
<form id="contact-form" name="contact-form" action="assets/php/send.php" method="post" novalidate="novalidate">
<fieldset>
<div id="alert-area"></div>
<input class="col-sm-6 col-xs-12" id="fname" type="text" name="fname" placeholder="first name">
<input class="col-sm-6 col-xs-12" id="lname" type="text" name="lname" placeholder="last name">
<input class="col-sm-6 col-xs-12" id="number" type="text" name="number" placeholder="number">
<input class="col-sm-6 col-xs-12" id="email" type="text" name="email" placeholder="email">
<input class="btn btn-default blue" id="submit" type="submit" name="submit" value="Submit" onclick="ga('send', 'event', ‘scholars’, 'click', ‘s-rs’);">
<div id='response'></div>
</fieldset>
</form>
<form id="contact-form" name="contact-form" action="assets/php/send.php" method="post" novalidate="novalidate">
<fieldset>
<div id="alert-area"></div>
<input class="col-sm-6 col-xs-12" id="fname" type="text" name="fname" placeholder="first name">
<input class="col-sm-6 col-xs-12" id="lname" type="text" name="lname" placeholder="last name">
<input class="col-sm-6 col-xs-12" id="number" type="text" name="number" placeholder="number">
<input class="col-sm-6 col-xs-12" id="email" type="text" name="email" placeholder="email">
<input class="btn btn-default blue" id="submit" type="submit" name="submit" value="Submit" onclick="ga('send', 'event', ‘scholars’, 'click', ‘s-rs’);">
<div id='response'></div>
</fieldset>
</form>
send.php
<?php
$api_key = 'XXXXXXXXX';
$list_id = 'XXXXXXXXXX';
// Include the MailChimp API wrapper
include('./inc/MailChimp.php');
// Then call/use the class
use \DrewM\MailChimp\MailChimp;
$MailChimp = new MailChimp($api_key);
// Submit subscriber data to MailChimp
$result = $MailChimp->post("lists/$list_id/members", [
'email_address' => $_POST["email"],
'merge_fields' => ['FNAME'=>$_POST["fname"], 'LNAME'=>$_POST["lname"], 'NUMBER'=>$_POST["number"]],
'status' => 'subscribed',
]);
if ($MailChimp->success()) {
// Success message
echo "<h4>Thank you for your interest. </h4>";
} else {
// Display error
echo "<h4>Whoops! Please try again.</h4>";
}
?>
Validate function
function validateForm(){
$('form').each(function(){
$(this).validate({
// all fields are required
rules: {
fname: {
required: true
},
lname: {
required: true
},
email: {
required: true,
email: true
},
number: {
required: true,
number: true
}
},
// if valid, post data via AJAX
submitHandler: function(form){
$.post("assets/php/send.php", {
fname: $("#fname").val(),
lname: $("#lname").val(),
email: $("#email").val(),
number: $("#number").val()
}, function (data) {
$('#response').html(data);
});
}
})
})
}
This works fine for the first form but gives a "Uncaught SyntaxError: Invalid or unexpected token" for other forms
The SyntaxError was because of rogue quote marks in the ga onCLick event.
Solved the multiple form submit issue with the following jQuery code
function validateForm(){
$('form').each(function(){
$(this).validate({
// all fields are required
rules: {
fname: {
required: true
},
lname: {
required: true
},
email: {
required: true,
email: true
},
number: {
required: true,
number: true
}
},
// if valid, post data via AJAX
submitHandler: function (form) {
$.post("assets/php/send.php", $(form).serializeArray().reduce(function(obj, item) {
obj[item.name] = item.value;
return obj;
}, {})
, function (data) {
$(form).find('#response').html(data);
});
}
})
})
}
All forms have unique ID. This code works with modal form too. Hope this helps!
I am trying to use jquery validation for a php form to change your password but I keep getting the error "Your password must be the same as above" when the password is correct. I can't seem to find out where I have went wrong at all... Here's the JS code
var changepassword = function() {
return {
init: function() {
/*
* Jquery Validation, https://github.com/jzaefferer/jquery-validation
*/
$('#changepassword').validate({
errorClass: 'help-block animation-slideUp',
errorElement: 'div',
errorPlacement: function(error, e) {
e.parents('.form-group > div').append(error);
},
highlight: function(e) {
$(e).closest('.form-group').removeClass('has-success has-error').addClass('has-error');
$(e).closest('.help-block').remove();
},
success: function(e) {
if (e.closest('.form-group').find('.help-block').length === 2) {
e.closest('.help-block').remove();
} else {
e.closest('.form-group').removeClass('has-success has-error');
e.closest('.help-block').remove();
}
},
rules: {
'newpassword': {
required: true,
minlength: 6
},
'newpassword-verify': {
equalTo: '#newpassword',
required: true
}
},
messages: {
'newpassword': {
required: 'Please provide a password',
minlength: 'Your password must be at least 6 characters long'
},
'newpassword-verify': {
required: 'Please provide a password',
minlength: 'Your password must be at least 6 characters long',
equalTo: 'Please enter the same password as above'
}
}
});
}
};
}();
This is the PHP/HTML for the form
<form method="POST" class="form-horizontal form-bordered" id="changepassword">
<div class="form-group">
<label class="col-md-3 control-label" for="newpassword">New Password</label>
<div class="col-md-6">
<input type="password" id="newpassword" name="newpassword" class="form-control" placeholder="New Password" required>
</div>
</div>
<!-- This is where I keep getting the error -->
<div class="form-group">
<label class="col-md-3 control-label">Repeat Password</label>
<div class="col-md-6">
<input type="password" id="newpassword-verify" name="newpassword-verify" class="form-control" placeholder="Repeat Password" required>
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label" for="oldpassword">Current Password</label>
<div class="col-md-6">
<input type="password" id="oldpassword" name="oldpassword" class="form-control" placeholder="Password" required>
</div>
</div>
<div class="form-group form-actions">
<button type="submit" name="update" class="btn btn-block btn-primary">Update</button>
</div>
</form>
Sorry, I was able to fix it by making a new file called settings1.php then removing the old one and renaming the new one with the old name.
I'm facing some problems with jQuery Validate. I've already put the rules but when i'm submitting the form, nothing happens.
I'm using ASP.NET MVC 4 and Visual Studio 2010.
EDIT: Click here to see my entire code. I'm trying to post it here but i'm getting the following error: 403 Forbidden: IPS signature match. Below is part of my code with Andrei Dvoynos's suggestion. I'm getting the same error. Clicking on submit and the page being reloaded
#{
ViewBag.Title = "Index";
}
#section Teste1{
<script type="text/javascript">
$(document).ready(function () {
$("#moeda").maskMoney();
$("#percent").maskMoney();
$(":input").inputmask();
$('#tel').focusout(function () {
var phone, element;
element = $(this);
element.unmask();
phone = element.val().replace(/\D/g, '');
if (phone.length > 10) {
element.inputmask({ "mask": "(99) 99999-999[9]" });
} else {
element.inputmask({ "mask": "(99) 9999-9999[9]" });
}
}).trigger('focusout');
//the code suggested by Andrei Dvoynos, i've tried but it's occurring the same.
$("#form1").validate({
rules: {
cpf: { required: true, },
cep: { required: true, },
tel: { required: true, },
email: { required: true, },
cnpj: { required: true, },
},
highlight: function (element) {
$(element).closest('.form-group').addClass('has-error');
},
unhighlight: function (element) {
$(element).closest('.form-group').removeClass('has-error');
},
errorElement: 'span',
errorClass: 'help-block'
});
});
</script>
}
#using (#Html.BeginForm("", "", FormMethod.Post,
new { id = "form1", name = "form1" }))
{
<fieldset>
<legend>Sign In</legend>
<div class="form-group" id="divCpf">
<label for="cpf">CPF</label>
<input data-inputmask="'mask': '999.999.999-99'" class="form-control" id="cpf" />
</div>
<div class="form-group" id="divCep">
<label for="cep">CEP</label>
<input data-inputmask="'mask' : '99999-999'" type="text" class="form-control" id="cep" placeholder="CEP" />
</div>
<div class="form-group" id="divTel">
<label for="tel">Telefone</label>
<input type="text" class="form-control" id="tel" placeholder="tel" />
</div>
<div class="form-group" id="email">
<label for="email">Email</label>
<input type="text" class="form-control" id="email" placeholder="Email" />
</div>
<div class="form-group" id="divcnpj">
<label for="cnpj">CNPJ</label>
<input data-inputmask="'mask' : '99.999.999/9999-99'" type="text" class="form-control" id="cnpj" placeholder="CNPJ" />
</div>
<div class="form-group">
<label for="moeda">Moeda</label>
<input type="text" id="moeda" data-allow-zero="true" class="form-control" />
</div>
<div class="form-group">
<label for="Percent">Percent</label>
<input type="text" id="percent" data-suffix="%" data-allow-zero="true" class="form-control" maxlength="7" />
</div>
<input type="submit" class="btn btn-default" value="Sign In" id="sign" />
</fieldset>
}
My tests (all unsuccessful):
1 - put the $("form").validate() into $(document).ready()
2 - put the required class on the fields.
jQuery Validate plugin version: 1.13.0
In addition to the fatal problem you fixed thanks to #Andrei, you also have one more fatal flaw. The name attribute is missing from your inputs.
Every element must contain a unique name attribute. This is a requirement of the plugin because it's how it keeps track of every input.
The name is the target for declaring rules inside of the rules option.
$("#form1").validate({
rules: { // <- all rule declarations must be contained within 'rules' option
cpf: { // <- this is the NAME attribute
required: true,
....
DEMO: http://jsfiddle.net/3tLzh/
You're missing the rules property when calling the validate function, try something like this:
$("#form1").validate({
rules: {
cpf: { required: true, },
cep: { required: true, },
tel: { required: true, },
email: { required: true, },
cnpj: { required: true, },
},
highlight: function (element) {
$(element).closest('.form-group').addClass('has-error');
},
unhighlight: function (element) {
$(element).closest('.form-group').removeClass('has-error');
},
errorElement: 'span',
errorClass: 'help-block'
});