Jquery Validation Resets page - javascript

i'm new to using javascript plugins to validate data in forms and therefore am having problems. Currently, the first validation works fine and executes the correct jquery, however the second validation for the second section of the form resets the page when valid data is entered.
Here's a jsfiddle to demonstrate the problem:
http://jsfiddle.net/epn63vk3/2/
You can also check out the version with the css fully working at :
http://178.62.85.190/index.html
Javascript:
<script type="text/javascript">
$(document).ready(function () {
$("#buttonToSecondaryDetailsSection").click(function (e) {
$('#primaryDetailsForm').validate({ // initialize the plugin
rules: {
forenameInput: {
required: true,
minlength: 2
},
surnameInput: {
required: true,
minlength: 2
},
emailInput: {
required: true,
email: true
}
}
});
var primaryValid = $('#primaryDetailsForm').valid();
if (primaryValid) {
e.preventDefault();
$("#primaryDetailsForm").slideUp("slow");
$("#secondaryDetailsForm").slideDown("slow");
} else {
}
});
$("#buttonToCommentsSection").click(function (f) {
$('#secondaryDetailsForm').validate({ // initialize the plugin
rules: {
telephoneInput: {
required: true,
minlength: 11,
maxlength: 11
},
genderInput: {
required: true,
},
dobInput: {
required: true,
dateFormat: true
}
}
});
var secondaryValid = $('#secondaryDetailsForm').valid();
if (secondaryValid) {
f.preventDefault();
$("#secondaryDetailsForm").slideUp("slow");
$("#commentsDetailsForm").slideDown("slow");
} else {
}
});
});
Forms :
<div id = "sections">
<div id = "titlePanel">
<p id = "sectionTitle">
Step 1: Your primary details
</p>
</div>
<form id = "primaryDetailsForm" method = "POST">
<label for "forenameInput" id = "labels"> First Name </label>
<br>
<input id = "forenameInput" name = "forenameInput" type = "text" class = "input-block-level">
<br>
<label for "surnameInput" id = "label1"> Surname </label>
<br>
<input id = "surnameInput" name = "surnameInput" type = "text" class = "input-block-level">
<br>
<label for "emailInput" id = "label2"> Email Address:</label>
<br>
<input id = "emailInput" name = "emailInput" type = "email" class = "input-block-level">
<br>
<div id = "registrationButtonWrapper">
<button id = "buttonToSecondaryDetailsSection" class = "btn btn-default"> next > </button>
</div>
</form>
</div>
<div id = "Div1">
<div id = "Div2">
<p id = "P1">
Step 2: Additional details
</p>
</div>
<form id = "secondaryDetailsForm" method = "POST">
<label for "telephoneInput" id = "label3"> Telephone Number </label>
<br>
<input id = "telephoneInput" name = "telephoneInput" type = "number" class = "input-block-level">
<br>
<label for "genderInput" id = "label4"> Gender </label>
<br>
<select id = "genderInput" name="genderInput">
<option value="male"> Male </option>
<option value="female"> Female </option>
</select>
<br>
<label for "dateOfBirthInput" id = "label5"> Date Of Birth </label>
<br>
<input id = "dateOfBirthInput" name = "dobInput" type = "date" class = "input-block-level">
<br>
<div id = "Div3">
<button id = "buttonToCommentsSection" class = "btn btn-default" > next > </button>
</div>
</form>
</div>

Firstly you are adding the validation on each click, you should first check if it was added. Also the date validation looks like its failing. Where is dateFormat from? If you use date it will work.

Related

Nodemailer script does not execute when called from the website

I'm trying to use Nodemailer to send emails by clicking submit on a web form. The test strings of the embedded script are being printed, but after that the script fails with this message in the console:
ReferenceError: require is not defined
What's interesting is that I receive emails from this script when I run it directly from the terminal, but when I try to trigger it from my web form, I get this error.
Almost everywhere I've looked people present a script such as the one directly below as being the only thing needed to send emails using Nodemailer. Neither the Nodemailer website nor W3Schools make reference to anything else. What am I missing?
Thank you for your time,
-Joel
<script>
const myForm = document.getElementById('myForm');
console.log("Testing!");
myForm.addEventListener("click", () => {
var nodemailer = require('nodemailer');
var transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: 'angleritemailer#gmail.com',
pass: 'hammertime80'
}
});
const mailOptions = {
from: 'angleritemailer#gmail.com',
to: 'joelnashjobs#yahoo.com',
subject: 'hey',
text : 'text',
html: '<p>Your html here</p>'
}
transporter.sendMail(mailOptions, function(err, info) {
if (err)
console.log(err)
else
console.log(info);
});
});
</script>
<form" class = "col-sm-6" action = "/" method = "POST" id = "myForm">
<div class = "row form-row form-group">
<div class = "col-sm-5">
<input type = "text" class = "form-control-plaintext full-width" id = "name" placeholder = "Your name here">
</div>
<div class = "col-sm-2">
</div>
<div class = "col-sm-5 widen-slightly">
<input type = "text" class = "form-control-plaintext full-width" id = "staticEmail" placeholder = "email#example.com">
</div>
</div>
<div class = "row form-row form-group">
<div class = "col-sm-12 widen-slightly">
<input type = "text" class = "form-control-plaintext full-width" id = "phone" placeholder = "Phone number with area code">
</div>
</div>
<div class = "row form-row form-group">
<div class = "col-sm-12 widen-slightly">
<input type = "text" class = "form-control-plaintext full-width" id = "subject" placeholder = "Subject">
</div>
</div>
<div class = "row form-row form-group">
<div class = "col-sm-12 widen-slightly">
<textarea rows = "6" class = "form-control-plaintext full-width" id = "Description" placeholder = "Description"></textarea>
</div>
</div>
<div class = "row form-row form-group">
<label class = "col-sm-3 col-form-label" >Any Photos</label>
<div class = "col-sm-7">
<input type = "file" class = "form-control-file full-width" id = "">
</div>
<div class = "cl-sm-2">
<button type="submit" class="btn btn-default" id = "submit">Submit</button>
</div>
</div>
</form>

how to pass the input type in jQuery to ajax

I have a basic bootstrap form, and I want to pass the input type through to php via ajax. I can get the input name & value with serializeArray().
How would I extend the output from serializeArray to also include the input 'type'?
Some more info... Here's my current form...
<form id="second_example_form" class="form-horizontal core_form_submission" action="#" method="post" data-callback="<?php echo __DIR__ . '/form-second-example.callback.php'; ?>">
<div class="form-group">
<label class="col-sm-2 control-label" for="email">Email</label>
<div class="col-sm-5">
<input id="email" class="form-control" required type="email" placeholder="Email" name="email">
</div>
<div class="col-sm-5 messages"></div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-default">Submit</button>
</div>
</div>
And here's the ajax calling js...
$('#form').on('submit', function(e) {
e.preventDefault();
var data = form.serializeArray();
$.post('ajax/forms.ajax.php', {
data: data
}, function(r) {
var json = JSON.parse(r);
}
});
var data = form.serializeArray(); works great to pass the name and value... but doesn't include input type.
Can anyone help?
Serialize does not provide that, you would have to construct name value of all the types and pass that to your server.
$('form').on('submit', function(e) {
e.preventDefault();
var formData = $(this).serializeArray();
$('input, select', this).each(function() {
formData.push({
name: $(this).attr('name') + '_type',
value: $(this).prop('tagName').toLowerCase()
});
});
console.log(formData);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="second_example_form" class="form-horizontal core_form_submission" action="#" method="post" data-callback="<?php echo __DIR__ . '/form-second-example.callback.php'; ?>">
<div class="form-group">
<label class="col-sm-2 control-label" for="email">Email</label>
<div class="col-sm-5">
<input id="email" class="form-control" required type="email" placeholder="Email" name="email">
</div>
<div class="col-sm-5 messages"></div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-default">Submit</button>
</div>
</div>
</form>
You can not do this normal serializeArray function I did quick fix and sharing code with two alternative.
$(document).ready(function(){
//Make sure name and id will be same id=email_email name = email_email
var fields = $( "#second_example_form" ).serializeArray();
fields = fields.map(function(val){
val.type = $( "#"+val.name ).attr("type");
return val;
});
console.log(fields);
//Change only name and add type with name seprated by _ like this name = name_type
var fields = $( "#second_example_form" ).serializeArray();
fields = fields.map(function(val){
val.type = val.name.split("_")[1]
return val;
});
console.log(fields);
});
body, select {
font-size: 14px;
}
form {
margin: 5px;
}
p {
color: red;
margin: 5px;
}
b {
color: blue;
}
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<form id="second_example_form" class="form-horizontal core_form_submission" action="#" method="post" data-callback="<?php echo __DIR__ . '/form-second-example.callback.php'; ?>">
<div class="form-group">
<label class="col-sm-2 control-label" for="email">Email</label>
<div class="col-sm-5">
<input id="email_email" class="form-control" required type="email" placeholder="Email" name="email_email">
</div>
<div class="col-sm-5 messages"></div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-default">Submit</button>
</div>
</div>
</form>
I ended up doing a mixture of the other answers, to create a new array from scratch.
// Collect all of the fields in the form, their values and types
function gather_form_fields(form)
{
var output = {};
form.find(':input').each(function(){
var type = $(this).attr('type'),
name = $(this).attr('name'),
val = $(this).val();
// If it's a select or other element without a 'type', return the element
if (type == null) {
type = $(this).prop('tagName').toLowerCase();
}
// remove the submit button
if (type == 'submit') {
return true;
}
output[name] = {
type: type,
name: name,
value: val
};
});
return output;
}
This then produces an object with the type, name and value e.g.
data = {
first_name: {
name: "first_name",
type: "text",
value: "joe"
},
email: {
name: "email",
type: "email",
value: "jbloggs#test.com"
}
}
You can send the type within the value or the name.
In your php you can use explode to separate the type from the value/name. Here's how to send it within the value.
$('#form').on('submit', function(e) {
e.preventDefault();
var fields = e.serializeArray();
for(var i = 0; i < fields.length; i++){
var item = e.find(':input').eq(i);
var fieldType = item.attr("type") === null ? item.prop("tagName") : item.attr("type");
fieldType = fieldType === null ? item.prop("tagName") : fieldType;
data.push({"name": fields[i].name, "value": fieldType + "|" + fields[i].value })
}
$.post('ajax/forms.ajax.php', {
data: data
}, function(r) {
var json = JSON.parse(r);
}
});

Pulling value from a serialized array - Form Validation

I have a form:
<form role="form" id="emailForm" action="#" th:action="#{/emailSubmission}" th:object="${university}" method="post">
<div class="form-group">
<input type="hidden" th:field="*{id}" ></input>
<p>
<label for="emailID"><span class="glyphicon glyphicon-envelope"></span> Email</label>
<input type="email" class="form-control" name="emailID" id="emailID" field="email" th:field="*{email}" placeholder="Enter email"></input></p>
<p>
<label for="uniID"><span class="glyphicon glyphicon-book"></span> University Name</label>
<input type="text" class="form-control" name="uniID" id="uniID" field="uniName" th:field="*{uniName}" placeholder="Enter University Name"></input></p>
<p>
<label for="adminID"><span class="glyphicon glyphicon-user"></span> Administrator name</label>
<input type="text" class="form-control" name="adminID" id="adminID" field="adminName" th:field="*{adminName}" placeholder="Enter Aministrator Name"></input></p>
</div>
<button type="button" id="submitButton" class="btn btn-default btn-success btn-block" data-dismiss="modal" ><span class="glyphicon glyphicon-check"></span> Register</button>
</form>
And some jQuery:
//submit form validation
$("#submitButton").click(function(event) {
var form_data = $("#emailForm").serializeArray();
var error_free = true;
for (var input in form_data) {
var element = $('#' + form_data[input]['name']);
var valid = element.hasClass("is-valid");
if (!valid) {
error_free = false;
}
}
if (!error_free) {
event.preventDefault();
} else {
sendEmail();
};
});
My problem is with the line:
var element=$('#' + form_data[input]['name']);
It'm trying to return $('#emailID') etc but can't seem to get this to work. Any help would be appreciated.
After talking with you in the comment, here is the output of your form_data var :
Array(4)
0 : {name: "id", value: "0"}
1 : {name: "email", value: "test#uni.ac.uk"}
2 : {name: "uniName", value: "aUni"}
3 : {name: "adminName", value: "anAdmin"}
According to your HTML, it refered to your "field" attr and not your "name", so to select them, change this :
var element = $('#' + form_data[input]['name']);
to this :
var element = $("input[field='" + form_data[input]['name'] + "']");
or this (as suggested in the comment by #Taplar) :
var element = $('input').filter('[field="'+ form_data[input]['name'] +'"]');
Is it ok for you?

How validate array input angularjs

i repeated array of input by ng-repeat and want to validate by angular.
my input form is such as this. How validate array of inputs.
thanks.
<div ng-repeat="item in items track by $index">
<input name = "apartment.home[$index].name" ng-model='item.name' required>
<span ng-show="apartment.home[$index].name.$error.required">
name is required.</span>
<input name = "apartment.home[$index].phone" ng-model='item.phone'>
</div>
There is an example for the usage. Here is the list:
<input
ng-model="string"
[name="string"]
[required="string"]
[ng-required="boolean"]
[ng-minlength="number"]
[ng-maxlength="number"]
[ng-pattern="string"]
[ng-change="string"]
[ng-trim="boolean"]>
...
</input>
And here is an example:
<script>
angular.module('inputExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.user = {name: 'guest', last: 'visitor'};
}]);
</script>
<div ng-controller="ExampleController">
<form name="myForm">
<label>
User name:
<input type="text" name="userName" ng-model="user.name" required>
</label>
<div role="alert">
<span class="error" ng-show="myForm.userName.$error.required">
Required!</span>
</div>
<label>
Last name:
<input type="text" name="lastName" ng-model="user.last"
ng-minlength="3" ng-maxlength="10">
</label>
<div role="alert">
<span class="error" ng-show="myForm.lastName.$error.minlength">
Too short!</span>
<span class="error" ng-show="myForm.lastName.$error.maxlength">
Too long!</span>
</div>
</form>
<hr>
<tt>user = {{user}}</tt><br/>
<tt>myForm.userName.$valid = {{myForm.userName.$valid}}</tt><br/>
<tt>myForm.userName.$error = {{myForm.userName.$error}}</tt><br/>
<tt>myForm.lastName.$valid = {{myForm.lastName.$valid}}</tt><br/>
<tt>myForm.lastName.$error = {{myForm.lastName.$error}}</tt><br/>
<tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
<tt>myForm.$error.minlength = {{!!myForm.$error.minlength}}</tt><br/>
<tt>myForm.$error.maxlength = {{!!myForm.$error.maxlength}}</tt><br/>
</div>
and a .js example:
var user = element(by.exactBinding('user'));
var userNameValid = element(by.binding('myForm.userName.$valid'));
var lastNameValid = element(by.binding('myForm.lastName.$valid'));
var lastNameError = element(by.binding('myForm.lastName.$error'));
var formValid = element(by.binding('myForm.$valid'));
var userNameInput = element(by.model('user.name'));
var userLastInput = element(by.model('user.last'));
it('should initialize to model', function() {
expect(user.getText()).toContain('{"name":"guest","last":"visitor"}');
expect(userNameValid.getText()).toContain('true');
expect(formValid.getText()).toContain('true');
});
it('should be invalid if empty when required', function() {
userNameInput.clear();
userNameInput.sendKeys('');
expect(user.getText()).toContain('{"last":"visitor"}');
expect(userNameValid.getText()).toContain('false');
expect(formValid.getText()).toContain('false');
});
it('should be valid if empty when min length is set', function() {
userLastInput.clear();
userLastInput.sendKeys('');
expect(user.getText()).toContain('{"name":"guest","last":""}');
expect(lastNameValid.getText()).toContain('true');
expect(formValid.getText()).toContain('true');
});
it('should be invalid if less than required min length', function() {
userLastInput.clear();
userLastInput.sendKeys('xx');
expect(user.getText()).toContain('{"name":"guest"}');
expect(lastNameValid.getText()).toContain('false');
expect(lastNameError.getText()).toContain('minlength');
expect(formValid.getText()).toContain('false');
});
it('should be invalid if longer than max length', function() {
userLastInput.clear();
userLastInput.sendKeys('some ridiculously long name');
expect(user.getText()).toContain('{"name":"guest"}');
expect(lastNameValid.getText()).toContain('false');
expect(lastNameError.getText()).toContain('maxlength');
expect(formValid.getText()).toContain('false');
});
All taken from angularjs.org documentation.

how to validate a form tab wise, written in multiple tabs?

I have divided my form into 3 tabs and and when I click on next button it moves to the next tab and finally in the last tab when submit is clicked the whole form is getting validated which is also correct but my problem is that when I click next it must move to next tab only when the current tab validations are true.
Here is my form
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.13.0/jquery.validate.min.js"></script>
<form name="registration_form" id="registration_form" action="save.php" method="post">
<div id="tabs">
<ul>
<li>Basic Details</li>
<li>Employee Details</li>
<li>Address</li>
</ul>
<div id="tabs-1">
<div class="field">
<label>First Name</label>
<input type="text" name="first_name" id="first_name" />
<label>Last Name</label>
<input type="text" name="last_name" id="last_name" />
</div>
<div class="field">
<label>Age</label>
<input type="text" name="age" id="age"/>
</div>
<div class="field">
<input value="Next" type="button" id="next-1" name="1"/>
</div>
</div>
<div id="tabs-2">
<div class="field">
<label>Company</label>
<input type="text" name="company" id="company">
</div>
<div class="field">
<label>Designation</label>
<select name="designation" >
<option value="software developer">software developer</option>
<option value="software analyst">software analyst</option>
<option value="tester">tester</option>
</select>
</div>
<div class="field">
<label>Annual income</label>
<input type="text" name="income" id="income"> in Rupees
</div>
<div class="field">
<input value="Next" type="button" id="next-2" name="2" />
</div>
</div>
<div id="tabs-3">
<div class="field">
<label>Address</label>
<input type="text" name="address" id="address"
</div>
<div class="field">
<input type="submit" name="submit" value="SUBMIT" id="reg_submit" />
</div>
</div>
</div>
</form>
Javascript Validation code is
<script type="text/javascript">
$( "#tabs" ).tabs();
var validator = $("#registration_form").validate({ rules: {
first_name: {
required: true,
maxlength:30,
},
last_name: {
required: true,
maxlength:30,
},
age: {
digits:true,
},
company: {
required: true,
},
designation: {
required: true,
},
income: {
digits:true,
},
address: {
maxlength:100,
},
},
messages: {
first_name: {
required: "Please enter First Name",
maxlength: "maximum 30 characters are allowed",
},
last_name: {
required: "Please enter Last Name",
maxlength: "maximum 30 characters are allowed",
},
age: {
digits: "Enter only digits",
},
Company: {
required: "Please enter Company",
},
designation: {
required: "Please Select Designation",
},
income: {
digits: "Enter only digits",
},
address: {
maxlength: "Maximum of 100 characters are allowed",
},
}
});
// I have seen some examples in stack overflow and tried as below, but it is not working
var tabs = $("#tabs").tabs();
$('[id^=next-]').click(function() {
var tabid = $(this).attr('name');
var valid = true;
var i = 0;
var $inputs = $(this).children("div").find("input");
$inputs.each(function() {
if (!validator.element(this) && valid) {
validator.focusInvalid();
valid = false;
}
});
if (valid) {
var tabId = $(this).attr('name');
$( "#tabs" ).tabs( "option", "active", tabId );
}
});
$("input[id=reg_submit]").click(function() {
$(this).parents("form").submit();
});
please help,
Thanks
var next1 = false;
var next2 = false;
var next3 = false;
$('#next-1').on('click', function(){
//validate your inputs fields
var next1 = true;// assign true if validation is correct.
});
$('#next-2').on('click', function(){
//validate your inputs fields
var next2 = true;// assign true if validation is correct
});
$('#next-3').on('click', function(){
//validate your inputs fields
var next3 = true;// assign true if validation is correct
if((next1 == 'true') && (next2 == 'true') && (next3 == 'true'))
{
//submit form
}
})
try this example
Or Make three forms,

Categories