Server response message - javascript

I need to get server response error message to show in form after submit. I get message if i use this code in js
.error(function (data, status, header, config) {
$scope.postDataSuccessfully = false;
var messages = [];
angular.forEach(data.errors, function (value, key) {
$scope.ResponseDetails = "Data: " + data +
"<hr />status: " + status +
"<hr />headers: " + header +
"<hr />config: " + config;
messages.push('Error! ' + key + ' is not correct');
});
$scope.messages = messages;
});
and in html
<div ng-repeat="message in messages track by $index">
<div data-ng-hide="message == ''" data-ng-class="(postDataSuccessfully) ? 'alert alert-success' : 'alert alert-danger'">
{{message}}
</div>
</div>
but this is only shown on one place after submit, like on this image
I want to have message on field with error, like on next image
Here is my html code for this form input
<div class="form-group">
<label for="type" class="col-sm-3 control-label">{{'TYPE'| translate}}</label>
<div class="col-sm-9">
<select class="form-control" id="type" name="type" ng-model="type">
<option ng-repeat="type in types" value="{{type}}">{{type}}</option>
</select>
</div>
</div>
<div class="form-group">
<label for="description" class="col-sm-3 control-label">{{'DESCRIPTION'| translate}}</label>
<div class="col-sm-9">
<textarea type="text" rows="3" class="form-control" id="description" name="description" ng-model="description" placeholder="description"></textarea>
<br>
</div>
</div>

you have two options :
either you put for each field an error message and display it when it occur
<div ng-messages="myForm.myselect.$error" ng-if="myForm.$submitted || myForm.myselect.$touched">
<div ng-message="required">myselect is required.</div>
</div>
or alternatively you can use the toast popup error msgs :
$scope.validateMyData = function() {
var errorType = callYourServerService();
if(errorType === "myFirstField") {
toaster.pop('error', "Error", "Please insert valid value for myFirstField");
}
if(errorType === "mySecondField") {
toaster.pop('error', "Error", "Please insert valid value for mySecondField");
}
... etc

Related

Stop Mailchimp Custom Form Redirect On Submit With Email Validation Errors

I am using a custom mailchimp form with various validators. One validation that is derailing my form is the duplicate email validation.
The problem I'm having occurs when someone tries to subscribe to the list with a duplicate email that is already subscribed.
Instead of just staying on the page with a validation message stating something like: "already subscribed" it instead redirects the user to the mailchimp owned landing page version of the form.
Here is the form page: https://www.silverlinkfunding.com/color-me-mine.html
Here is where it redirects you: https://silverlinkfunding.us17.list-manage.com/subscribe/post?u=459fcc96e094a6b4dbe3e69f8&id=4afd1b9608
If you would like to test the form yourself feel free to use: stacktest#gmail.com
I was building the form using a guide from CSS tricks: https://css-tricks.com/form-validation-part-4-validating-mailchimp-subscribe-form/
Also, I don't know if this matters, but it's worth noting that this is being put on a weebly website using the embed code tool.
Here is my form code:
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.3.1/css/all.css" integrity="sha384-mzrmE5qonljUremFsqc01SB46JvROS7bZs3IO2EmfFsd15uHvIt+Y8vEf7N7fWAU" crossorigin="anonymous">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<style type="text/css">
.container-css {
background:#283184;
color: white;
clear:left;
width: 800px;
padding: 20px;
border-radius: 15px;
}
.form-text {
font-size: 19px;
}
.indicates-required{
margin-right: 20px;
}
.btn {
background-color: #339bff;
color: white;
margin-top: 10px;
}
.asterisk {
color: red;
}
.error-message {
color: red;
margin-top: 3px;
}
#media only screen
and (min-device-width: 320px)
and (max-device-width: 480px)
and (-webkit-min-device-pixel-ratio: 2)
and (orientation: portrait) {
.container-css {
width: 300px;
}
}
</style>
<div class="container container-css">
<form action="https://silverlinkfunding.us17.list-manage.com/subscribe/post?u=459fcc96e094a6b4dbe3e69f8&id=4afd1b9608" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank">
<div class="row d-flex justify-content-center">
<h2 class=>Apply Now</h2>
</div>
<div class="row d-flex justify-content-end">
<div class="indicates-required"><span class="asterisk">*</span> indicates required</div>
</div>
<!-- Name Row -->
<div class="row form-group">
<div class="col-sm-6">
<div class="row">
<div class="col-sm-12">
<label class="form-text" for="mce-FNAME">
<i class="fas fa-address-book"></i> First Name
<span class="asterisk">*</span></label>
<input class="form-control" type="text" name="FNAME" id="mce-FNAME" required>
</div>
</div>
</div>
<div class="col-sm-6">
<div class="row">
<div class="col-sm-12">
<label class="form-text" for="mce-LNAME">Last Name <span class="asterisk">*</span></label>
<input class="form-control" type="text" name="LNAME" id="mce-LNAME" required>
</div>
</div>
</div>
</div>
<!-- Email Row -->
<div class="row form-group">
<div class="col-sm-12">
<div class="row">
<div class="col-sm-12">
<label class="form-text" for="mce-EMAIL"><i class="fas fa-envelope"></i> Email Address
<span class="asterisk">*</span></label>
<input class="form-control" type="email" name="EMAIL" id="mce-EMAIL" title="The domain portion of the email address is invalid (the portion after the #)." pattern="^([^\x00-\x20\x22\x28\x29\x2c\x2e\x3a-\x3c\x3e\x40\x5b-\x5d\x7f-\xff]+|\x22([^\x0d\x22\x5c\x80-\xff]|\x5c[\x00-\x7f])*\x22)(\x2e([^\x00-\x20\x22\x28\x29\x2c\x2e\x3a-\x3c\x3e\x40\x5b-\x5d\x7f-\xff]+|\x22([^\x0d\x22\x5c\x80-\xff]|\x5c[\x00-\x7f])*\x22))*\x40([^\x00-\x20\x22\x28\x29\x2c\x2e\x3a-\x3c\x3e\x40\x5b-\x5d\x7f-\xff]+|\x5b([^\x0d\x5b-\x5d\x80-\xff]|\x5c[\x00-\x7f])*\x5d)(\x2e([^\x00-\x20\x22\x28\x29\x2c\x2e\x3a-\x3c\x3e\x40\x5b-\x5d\x7f-\xff]+|\x5b([^\x0d\x5b-\x5d\x80-\xff]|\x5c[\x00-\x7f])*\x5d))*(\.\w{2,})+$" required>
</div>
</div>
</div>
</div>
<!-- Phone Row -->
<div class="row form-group">
<div class="col-sm-12">
<div class="row">
<div class="col-sm-12">
<label class="form-text" for="mce-MMERGE3"><i class="fas fa-phone"></i> Phone
<span class="asterisk">*</span></label>
<input class="form-control" type="tel" name="MMERGE3" id="mce-MMERGE3" required>
</div>
</div>
</div>
</div>
<!-- Business, City, State Row -->
<div class="row form-group">
<div class="col-sm-12">
<div class="row">
<div class="col-sm-6">
<label class="form-text" for="mce-MMERGE4"><i class="fas fa-briefcase"></i> Business Name
<span class="asterisk">*</span></label>
<input class="form-control" type="text" name="MMERGE4" id="mce-MMERGE4" required>
</div>
<div class="col-sm-4">
<label class="form-text" for="mce-MMERGE5">City <span class="asterisk">*</span></label>
<input class="form-control" type="text" name="MMERGE5" id="mce-MMERGE5" required>
</div>
<div class="col-sm-2">
<label class="form-text" for="mce-MMERGE9">State <span class="asterisk">*</span></label>
<input class="form-control" type="text" name="MMERGE9" id="mce-MMERGE9" required>
</div>
</div>
</div>
</div>
<!-- Loan Row -->
<div class="row form-group">
<div class="col-sm-12">
<div class="row">
<div class="col-sm-6">
<label class="form-text" for="mce-MMERGE7"><i class="fas fa-money-bill-alt"></i> Loan Amount Requested
<span class="asterisk">*</span></label>
<input class="form-control" type="text" name="MMERGE7" id="mce-MMERGE7" required>
</div>
<div class="col-sm-6">
<label class="form-text" for="mce-MMERGE8">Cash Available For Investment <span class="asterisk">*</span></label>
<input class="form-control" type="text" name="MMERGE8" id="mce-MMERGE8" required>
</div>
</div>
</div>
</div>
<!-- real people should not fill this in and expect good things - do not remove this or risk form bot signups-->
<div style="position: absolute; left: -5000px;" aria-hidden="true"><input type="text" name="b_459fcc96e094a6b4dbe3e69f8_4afd1b9608" tabindex="-1" value=""></div>
<div class="clear d-flex justify-content-center"><input type="submit" value="Apply Now" name="subscribe" id="mc-embedded-subscribe" class="button btn"></div>
</form>
</div>
<!-- JS -->
<script>
// Add the novalidate attribute when the JS loads
var forms = document.querySelectorAll('.validate');
for (var i = 0; i < forms.length; i++) {
forms[i].setAttribute('novalidate', true);
}
// Validate the field
var hasError = function (field) {
// Don't validate submits, buttons, file and reset inputs, and disabled fields
if (field.disabled || field.type === 'file' || field.type === 'reset' || field.type === 'submit' || field.type === 'button') return;
// Get validity
var validity = field.validity;
// If valid, return null
if (validity.valid) return;
// If field is required and empty
if (validity.valueMissing) return 'Please fill out this field.';
// If not the right type
if (validity.typeMismatch) {
// Email
if (field.type === 'email') return 'Please enter an email address.';
// URL
if (field.type === 'url') return 'Please enter a URL.';
}
// If too short
if (validity.tooShort) return 'Please lengthen this text to ' + field.getAttribute('minLength') + ' characters or more. You are currently using ' + field.value.length + ' characters.';
// If too long
if (validity.tooLong) return 'Please shorten this text to no more than ' + field.getAttribute('maxLength') + ' characters. You are currently using ' + field.value.length + ' characters.';
// If pattern doesn't match
if (validity.patternMismatch) {
// If pattern info is included, return custom error
if (field.hasAttribute('title')) return field.getAttribute('title');
// Otherwise, generic error
return 'Please match the requested format.';
}
// If number input isn't a number
if (validity.badInput) return 'Please enter a number.';
// If a number value doesn't match the step interval
if (validity.stepMismatch) return 'Please select a valid value.';
// If a number field is over the max
if (validity.rangeOverflow) return 'Please select a value that is no more than ' + field.getAttribute('max') + '.';
// If a number field is below the min
if (validity.rangeUnderflow) return 'Please select a value that is no less than ' + field.getAttribute('min') + '.';
// If all else fails, return a generic catchall error
return 'The value you entered for this field is invalid.';
};
// Show an error message
var showError = function (field, error) {
// Add error class to field
field.classList.add('error');
// If the field is a radio button and part of a group, error all and get the last item in the group
if (field.type === 'radio' && field.name) {
var group = field.form.querySelectorAll('[name="' + field.name + '"]');
if (group.length > 0) {
for (var i = 0; i < group.length; i++) {
group[i].classList.add('error');
}
field = group[group.length - 1];
}
}
// Get field id or name
var id = field.id || field.name;
if (!id) return;
// Check if error message field already exists
// If not, create one
var message = field.form.querySelector('.error-message#error-for-' + id );
if (!message) {
message = document.createElement('div');
message.className = 'error-message';
message.id = 'error-for-' + id;
// If the field is a radio button or checkbox, insert error after the label
var label;
if (field.type === 'radio' || field.type ==='checkbox') {
label = field.form.querySelector('label[for="' + id + '"]') || field.parentNode;
if (label) {
label.parentNode.insertBefore( message, label.nextSibling );
}
}
// Otherwise, insert it after the field
if (!label) {
field.parentNode.insertBefore( message, field.nextSibling );
}
}
// Add ARIA role to the field
field.setAttribute('aria-describedby', 'error-for-' + id);
// Update error message
message.innerHTML = error;
// Show error message
message.style.display = 'block';
message.style.visibility = 'visible';
};
// Remove the error message
var removeError = function (field) {
// Remove error class to field
field.classList.remove('error');
// Remove ARIA role from the field
field.removeAttribute('aria-describedby');
// If the field is a radio button and part of a group, remove error from all and get the last item in the group
if (field.type === 'radio' && field.name) {
var group = field.form.querySelectorAll('[name="' + field.name + '"]');
if (group.length > 0) {
for (var i = 0; i < group.length; i++) {
group[i].classList.remove('error');
}
field = group[group.length - 1];
}
}
// Get field id or name
var id = field.id || field.name;
if (!id) return;
// Check if an error message is in the DOM
var message = field.form.querySelector('.error-message#error-for-' + id + '');
if (!message) return;
// If so, hide it
message.innerHTML = '';
message.style.display = 'none';
message.style.visibility = 'hidden';
};
// Listen to all blur events
document.addEventListener('blur', function (event) {
// Only run if the field is in a form to be validated
if (!event.target.form.classList.contains('validate')) return;
// Validate the field
var error = hasError(event.target);
// If there's an error, show it
if (error) {
showError(event.target, error);
return;
}
// Otherwise, remove any existing error message
removeError(event.target);
}, true);
// Check all fields on submit
document.addEventListener('submit', function (event) {
// Only run on forms flagged for validation
if (!event.target.classList.contains('validate')) return;
// Get all of the form elements
var fields = event.target.elements;
// Validate each field
// Store the first field with an error to a variable so we can bring it into focus later
var error, hasErrors;
for (var i = 0; i < fields.length; i++) {
error = hasError(fields[i]);
if (error) {
showError(fields[i], error);
if (!hasErrors) {
hasErrors = fields[i];
}
}
}
// If there are errrors, don't submit form and focus on first element with error
if (hasErrors) {
event.preventDefault();
hasErrors.focus();
}
// Otherwise, let the form submit normally
// You could also bolt in an Ajax form submit process here
}, false);
</script>
So my overall question is:
How can I keep duplicate email validation to the same page?
How do I prevent the duplicate email validation from redirecting to the mailchimp domain page?
Thanks for the assistance!

how to send email using asp.net and html page

I have a contact.html page where i have textboxex page for username,email,phone,subject, message and a submit button.
<form class="contact-page-form-1">
<div class="row clearfix">
<div class="col-md-6 col-sm-6 col-xs-12 form-group">
<input type="text" name="username" placeholder="Your Name*" id="username" required>
</div>
<div class="col-md-6 col-sm-6 col-xs-12 form-group">
<input type="email" name="email" placeholder="Email Address*" id="email" required>
</div>
<div class="col-md-6 col-sm-6 col-xs-12 form-group">
<input type="text" name="phone" placeholder="Phone Num" id="phone" required>
</div>
<div class="col-md-6 col-sm-6 col-xs-12 form-group">
<input type="text" name="subject" placeholder="Subject" id="subject" required>
</div>
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 form-group">
<textarea name="message" placeholder="Your Message..." id="message"></textarea>
</div>
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 form-group">
<button class="theme-btn btn-style-one" onclick="javascript:SendMail()" type="submit" name="submit-form">Send Message</button>
</div>
</div>
</form>
when we click on the button the javascript function is called where i Called a webmethod which is in VisionMail.aspx.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
function SendMail() {
var uname = document.getElementById("username").value;
var email = document.getElementById("email").value;
var phone = document.getElementById("phone").value;
var subject = document.getElementById("subject").value;
var message = document.getElementById("message").value;
var URL = "VisionMail.aspx?uname=" + uname + "&email=" + email + "&ph=" + phone + "&sub=" + subject + "&msg=" + message + "&count=India";
window.open(URL);
}
</script>
My WebMethod used for sending mail is in VisionMail.aspx as following:-
protected void Page_Load(object sender, EventArgs e)
{
string uname = Request.QueryString["uname"].ToString();
string email = Request.QueryString["email"].ToString();
string phone = Request.QueryString["ph"].ToString();
string subject = Request.QueryString["sub"].ToString();
string message = Request.QueryString["msg"].ToString();
string country = Request.QueryString["count"].ToString();
string close = #"<script type='text/javascript'>
window.returnValue = true;
window.close();
</script>";
using (MailMessage mail = new MailMessage())
{
mail.From = new MailAddress("abc#gmail.com");
mail.To.Add("info#xyz.com");
mail.Subject = subject;
mail.Body = "Mr. " + uname + "<br/>" + "Email ID : " + email + " Phone No. " + phone + "<br/> <h4>He/She is Sending Message From Contact Page (" + country + "). <br/>" + message;
mail.IsBodyHtml = true;
using (SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587))
{
try
{
smtp.Credentials = new NetworkCredential("abc#gmail.com", "abc123");
smtp.EnableSsl = true;
smtp.Send(mail);
base.Response.Write(close);
}
catch (Exception ex)
{
base.Response.Write(close);
}
}
}
}
This code is well on local system and mail is going but when i publish it on server it does not work and when i click on button to send mail, the mail does not go and the page which the webmethod present is downloaded. Is there any solution for this.
Try with below code.
using (SmtpClient smtp = new SmtpClient("smtp.gmail.com"))
{
try
{
smtp.Credentials = new NetworkCredential("visioncomn#gmail.com", "visioncomptel123");
smtp.EnableSsl = smtp.Port == 587 || smtp.Port == 465;
smtp.Send(mail);
base.Response.Write(close);
}
catch (Exception ex)
{
base.Response.Write(close);
}
}

Angularjs with rails API rest post 400 (bad request)

Hello i making a project of rails api and angularJs,And I found the following error.
angular.js:11821 POST http://localhost:3000/people 400 (Bad Request)
And I could not find why.
code below.
Rails Controller
# POST /people
def create
#person = Person.new(person_params)
if #person.save
render json: #person, status: :created, location: #person
else
render json: #person.errors, status: :unprocessable_entity
end
end
AngularJS
$scope.SendData = function () {
// use $.param jQuery function to serialize data from JSON
var data = $.param({
name: $scope.name,
age: $scope.age,
gender:$scope.gender,
lonlat:$scope.lonlat
});
var config = {
headers : {
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'
}
}
$http.post('http://localhost:3000/people', data, config)
.then(function (data, status, headers, config) {
$scope.PostDataResponse = data;
})
.catch(function (data, status, header, config) {
$scope.ResponseDetails = "Data: " + data +
"<hr />status: " + status +
"<hr />headers: " + header +
"<hr />config: " + config;
});
};
Html
<div ng-app="myApp" ng-controller="person">
<div class="modal-body">
<div class="form-group">
<label for="exampleInputEmail1">Name:</label>
<input type="text" class="form-control" name="name" ng-model="name" placeholder="Email">
</div>
<div class="form-group">
<label for="exampleInputEmail1">age:</label>
<input type="text" class="form-control" name="age" ng-model="age" placeholder="Email">
</div>
<div class="form-group">
<label for="exampleInputEmail1">gender:</label>
<input type="text" class="form-control" name="gender" ng-model="gender" placeholder="Email">
</div>
<div class="form-group">
<label for="exampleInputEmail1">lonlat:</label>
<input type="text" class="form-control" name="lonlat" ng-model="lonlat" placeholder="Email">
</div>
<button ng-click="SendData()"
class="btn btn-default">Submit</button>
{{ PostDataResponse }}
thanks for listening
I cannot see your person_params definition, but if it is like when produced by rails generators, you are missing to wrap your params in a person hash
var data = $.param({person:
{ name: $scope.name,
age: $scope.age,
gender:$scope.gender,
lonlat:$scope.lonlat }
});

How to change the url

I want to change the URL of the update operation. The end point of the URL should be gotten from an input. How can I achieve this? The following doesn't work.
$(document).ready(function(){
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return {"issue":o};
};
<form role="form">
<div class="form-group input-group">
<div class="row">
<div class="col-md-6">
<label>Issue ID * </label>
<select class="form-control selectclass" id="issueid"></select>
</div>
<div class="col-md-6">
<label>Tracker * </label>
<select class="form-control" name="tracker" id="tracker">
<option value="1">Bug</option>
<option value="2">Feature</option>
<option value="3">Support</option>
</select>
</div>
</div>
</div>
<div class="form-group">
<label>Subject </label>
<input class="form-control" placeholder="Issue Subject" name="subject" id="subject">
</div>
<div class="form-group">
<label>Description</label>
<textarea class="form-control" rows="6" name="description" id="description"></textarea>
</div>
<button type="submit" id="submit" class="btn btn-default">Submit Button</button>
<button type="reset" class="btn btn-default">Reset Button</button>
</form>
$('#submit').on('click', function(){
var x=document.getElementById('issueid').value;
$.ajax({
type : 'PUT',
url: 'http://localhost/redmine/issues'+ x +'.json',
contentType:'application/json',
data:JSON.stringify($('form').serializeObject()), // post data || get data
success : function(msg, status, jqXHR) {
console.log(msg, status, jqXHR);
},
error: function(xhr, resp, text) {
console.log(xhr, resp, text);
}
})
console.log(x);
});
});
Inputs are gotten from a form and sent to Redmine API. URL should look like below, http://localhost/redmine/issues/2.json
When dynamically populating your id="issueid" select make sure that you properly set the value attribute of the options:
$('.selectclass').append('<option value="' + value.id + '">' + value.id + '<option>');
Also fix the url for your next AJAX request by adding a trailing / after issues:
url: 'http://localhost/redmine/issues/' + x + '.json'

Username checking not working for form with multiple register models (mvc)

I have a page which allows an admin to add multiple users to the database at once, with usernames and passwords. I use remote username checking, so in my account models I have this:
public class RegisterModel
{
[Required]
[Display(Name = "User name")]
[System.Web.Mvc.Remote("doesUserNameExist", "Account", HttpMethod = "POST", ErrorMessage = "User name already exists. Please enter a different user name.")]
public string UserName { get; set; }
// ...etc
}
In my account controller I have this:
[HttpPost]
public JsonResult doesUserNameExist(string UserName)
{
var user = Membership.GetUser(UserName);
return Json(user == null);
}
Now this works nicely on a single form, with one user being created, using the mvc html helpers. The message saying that a username is in use shows up as I'm typing it into the field. But on this form which doesn't use the mvc helpers, instead pure html and javascript, it doesn't show up:
#model List<PicsWebApp.Models.UserRegisterModel>
#{
ViewBag.Title = "NewRep";
}
<div class="col-lg-12">
<h1>First-Time Setup</h1>
</div>
<legend></legend>
<div class="col-lg-12">
<h3>Add Representatives <small>You can add more representatives later</small></h3>
#using (Html.BeginForm("NewRep", "Admin", new { jobid = ViewData["jobid"] }, FormMethod.Post, new { #class = "form" }))
{
#Html.ValidationSummary(true)
<p>
Skip
<input type="submit" class="btn btn-primary" />
<button type="button" class="btn btn-default" id="add">Add Rep</button>
</p>
<div id="fieldform" class="col-lg-12">
<div id="container0" class="col-lg-4" style="background-color: #eee; border: 4px solid white;">
<h4 style="text-align: center">New Rep</h4>
<div class="form-group">
<label>Representative Name</label><input type="text" class="form-control" name="models[0].RepName" />
</div>
<div class="form-group">
<label>Contact Number</label><input type="text" class="form-control" name="models[0].ContactNumber" />
</div>
<div class="form-group">
<label>Rep Username</label><input type="text" class="form-control" name="models[0].UserName" />
<input class="text-box single-line" data-val="true" data-val-remote="User name already exists. Please enter a different user name." data-val-remote-additionalfields="*.UserName" data-val-remote-type="POST" data-val-remote-url="/Account/doesUserNameExist" data-val-required="The User name field is required." id="UserName" name="models[0].UserName" type="text">
<span class="field-validation-valid" data-valmsg-for="UserName" data-valmsg-replace="true"></span>
</div>
<div class="form-group">
<label>Location</label><select id="select-0" class="form-control" name="models[0].Location"></select>
</div>
<div class="form-group">
<label>Rep Password</label><input type="password" class="form-control" name="models[0].Password" />
</div>
<div class="form-group">
<label>Confirm Password</label><input type="password" class="form-control" name="models[0].ConfirmPassword" />
</div>
</div>
</div>
}
</div>
<script src="https://code.jquery.com/jquery.js"></script>
<script type="text/javascript">
var selectValues = {
"Johannesburg": "Johannesburg",
"Pretoria": "Pretoria",
"Cape Town": "Cape Town",
"Pretoria": "Pretoria",
"Durban": "Durban",
"Centurion": "Centurion"
};
$.each(selectValues, function (key, value) {
$('select')
.append($('<option>', { value: key })
.text(value))
.prop("selectedIndex", -1);
});
var i = 1;
$("#add").click(function () {
var inputfield = '<div class="col-lg-4" id="' + container + i + '" style="background-color: #eee; border: 4px solid white;"><h4 style="text-align: center">New Rep</h4><div class="form-group"><label>Representative Name</label><input type="text" class="form-control" name="models[' + i + '].RepName" /></div>' +
'<div class="form-group"><label>Contact Number</label><input type="text" class="form-control" name="models[' + i + '].ContactNumber" /></div>' +
'<div class="form-group"><label>Rep Username</label><input type="text" class="form-control" name="models[' + i + '].UserName" /></div>' +
'<div class="form-group"><label>Location</label><select id="select-' + i + '" class="form-control" name="models[' + i + '].Location"></select></div>' +
'<div class="form-group"><label>Rep Password</label><input type="password" class="form-control" name="models[' + i + '].Password" /></div>' +
'<div class="form-group"><label>Confirm Password</label><input type="password" class="form-control" name="models[' + i + '].ConfirmPassword"/></div></div>'
$('#fieldform').append(inputfield)
$.each(selectValues, function (key, value) {
$('#select-' + i)
.append($('<option>', { value: key })
.text(value))
.prop("selectedIndex", -1);
});
i++
});
</script>
I understand I would have to add validation attributes to the username input fields but I tried that and it still didn't work. Any ideas?
You could validate in your controller (when the ajax request is sent) using the Validator class. This class allows you to call Validator.TryValidateObject to validate your model's data annotations such as [Required].
Then once this has passed/failed return the constructed json data with success/error messages.
Here is the article that really helped me on this:
http://odetocode.com/blogs/scott/archive/2011/06/29/manual-validation-with-data-annotations.aspx

Categories