cshtml code for one of the textboxes. I'm trying to trigger a function on form submit that checks whether there's anything typed in the textboxes. If there isn't anything typed in the textboxes, the border should turn red.
#model WebForum.Models.AccountViewModel
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="~/Scripts/Custom.js"></script>
</head>
<h2 style="font-size:larger">CreateAccount</h2>
<p style="font-size:large">Please enter BOTH an account name and a password.</p>
<div id="account_create">
#using (Html.BeginForm("AccountCreated", "Home", FormMethod.Post, new { #id = "accountform" }, ))
{
#Html.TextBoxFor(Model => Model.Account_Name, new { #id = "account_name", #placeholder = "Your Account Name" })
<br />
<br />
#Html.TextBoxFor(Model => Model.Password, new { #id = "account_password", #placeholder = "Type Password Name" })
<br />
<br />
#Html.ValidationMessageFor(m => Model.Account_Name)
#Html.ValidationMessageFor(m => Model.Password)
<form id="accountform" onsubmit="accountform()">
<input type='submit' id="accountform" name="Create Account">
</form>
}
</div>
Heres the javascript file. The function should be triggered on ="onsubmit". I've tried various forms of .onsubmit, but they've haven't worked.
//run on form submit
function loginform() {
if ($('#account_name').val() == '') {
$('#account_name').css('border-color', 'red');
}
else {
$('#account_name').css('border-color', '');
}
if ($('#account_password').val() == '') {
$('#account_password').css('border-color', 'red');
}
else {
$('#account_password').css('border-color', '');
}
};
function accountform() {
if ($('#account_name').val() == '') {
$('#account_name').css('border-color', 'red');
}
else {
$('#account_name').css('border-color', '');
}
if ($('#account_password').val() == '') {
$('#account_password').css('border-color', 'red');
}
else {
$('#account_password').css('border-color', '');
}
};
function postform() {
if ($('#poster_name').val() == '') {
$('#poster_name').css('border-color', 'red');
}
else {
$('#poster_name').css('border-color', '');
}
if ($('#poster_text').val() == '') {
$('#poster_text').css('border-color', 'red');
}
else {
$('#poster_text').css('border-color', '');
}
};
function logwithoutform() {
if ($('#poster_text').val() == '') {
$('#poster_text').css('border-color', 'red');
}
else {
$('#poster_text').css('border-color', '');
}
};
And heres the controller code but that shouldn't be too important:
[HttpPost]
public ActionResult AccountCreated(Models.AccountViewModel model)
{
String Account_Name = model.Account_Name;
String Account_Password = model.Password;
if (!ModelState.IsValid)
{
return RedirectToAction("CreateAccount");
}
//if (Account_Name == null || Account_Password == null)
// return RedirectToAction("CreateAccount");
WebForumEntities2 db = new WebForumEntities2();
foreach(Account eachAccount in db.Accounts)
{
if (eachAccount.Account_Name.Equals(Account_Name))
{
return RedirectToAction("AccountCreatedMessage");
}
}
int nextiD = 0;
if (db.Accounts.ToList().Count > 0)
{
nextiD = db.Accounts.ToList().Last().Id + 1;
}
var newAccount = new Account();
newAccount.Account_Name = Account_Name;
newAccount.Password = Account_Password;
newAccount.Id = nextiD;
db.Accounts.Add(newAccount);
db.SaveChanges();
return RedirectToAction("CreateAccount");
}
Please help me make the textboxes turn red.
I've tried debugging, and the javascript functions are never called.
First I would use data attributes for field validation.
public class AccountViewModel
{
[Required] // data attribute
public string Account_Name;
[Required]
public string Password;
}
You can then submit your form normally. If the ASP.NET engine picks up any data validation errors it will put the class .field-validation-error on your inputs.
You can style this class to your liking, like so:
.field-validation-error
{
border-color: red;
}
A few other notes:
You have a form nested in another form, I would remove the form
around your button.
Not sure why you put your inputs into a string
in your controller instead of using your ViewModel.
I typically put my DbContext outside of my ActionResults, be sure to dispose of it.
Related
I am trying to store the users name, email and their message on my contact page. When i run my website and go on the contact page and type all the details inside the contact form and click the send button (send button called submitBtn) i get the error you can see below in the image.
error message:
c# code: this c# code is for the send button.
protected void submitBtn_Click(object sender, EventArgs e)
{
try
{
//Create the conection string and open the conn
SqlConnection conne = new SqlConnection(ConfigurationManager.ConnectionStrings["Fasthosts_MMConnectionString"].ConnectionString);
//Open the connection string
conne.Open();
//Get all the values from the text boxes etc and pass them over to the DB
string insertQuery = "insert into Contact(UserName, Email, Message) " +
"values(#UserName, #Email, #Message)";
SqlCommand com = new SqlCommand(insertQuery, conne);
//Get values from the controls such as the text boxes and pass them over to the DB
com.Parameters.AddWithValue("#UserName", tbUserName.Text);
com.Parameters.AddWithValue("#Message", userMessage.Text);
com.Parameters.AddWithValue("#Email", userEmail.Text);
//This actually executes the query with the given values above.
com.ExecuteNonQuery();
//Dispose the connection string once the data has been passed over the DB
conne.Close();
}
catch (Exception problem)
{
//throw Exception ;
Response.Write("Error Message: " + problem.ToString());
throw;
}
}
html code:
<div id="contactForm" class="contactForm">
<div id="formHeader" class="formHeader">
<h1 id="message">Contact Us :)</h1>
</div>
<div id="formBody" class="formBody">
<form action="homepage.aspx" method="POST" name="contactForm">
<div class="inputContainer">
<label for="userName">
<i class="fa fa-lg fa-fw fa-user"></i>
</label>
<asp:TextBox ID="tbUserName" placeholder="John Smith" runat="server"></asp:TextBox>
<!--<input name="name" id="userName" type="text" placeholder="John Smith">-->
</div>
<div class="inputContainer">
<label for="userEmail">
<i class="fa fa-lg fa-fw fa-envelope"></i>
</label>
<asp:TextBox ID="userEmail" placeholder="jsmith#domain.com" runat="server"></asp:TextBox>
</div>
<div class="inputContainer">
<asp:TextBox ID="userMessage" rows="10" placeholder="Enter your message" runat="server" Height="100px"></asp:TextBox>
</div>
<!--<input id="submitBtn1" class="submitBtn" type="submit" value="Send">-->
<asp:Button ID="submitBtn" Class="submitBtn" runat="server" Text="Send" OnClick="submitBtn_Click" />
</form>
</div>
javascript code :
(function () {
"use strict";
var //GLOBAL VARIABLES
input,
container,
//CSS CLASSES
classSuccess = "success",
classError = "error",
//FORM VALIDATOR
formValidator = {
init: function () {
this.cacheDom();
this.bindEvents();
},
cacheDom: function () {
//MAIN PARENT ELEMENT
this.contactForm = document.getElementById("contactForm");
//MAIN FORM ELEMENTS
this.formHeader = document.querySelector("#formHeader h1");
this.formBody = document.getElementById("formBody");
this.inputContainer = document.getElementsByClassName("inputContainer");
//USER INPUT ELEMENTS
//INPUT FIELDS
this.fields = {
userName: document.getElementById("userName"),
userEmail: document.getElementById("userEmail"),
userMessage: document.getElementById("userMessage")
};
this.submitBtn = document.getElementById("submitBtn");
},
bindEvents: function () {
var i;
//RUN RULES ON SUBMIT BUTTON CLICK
this.submitBtn.onclick = this.runRules.bind(this);
//BIND EVENTS TO EACH INPUT FIELD
for (i in this.fields) {
if (this.fields.hasOwnProperty(i)) {
//VARIABLES
input = this.fields[i];
container = input.parentElement;
//RUN RULES WHEN INPUT HAS FOCUS
input.onfocus = this.runRules.bind(this);
//RESET ERRORS WHEN CONTAINER IS CLICKED
container.onclick = this.resetErrors.bind(this, input);
}
}
},
runRules: function (evnt) {
var target = evnt.target,
type = evnt.type;
//IF EVENT ON SUBMIT BUTTON
if (target === this.submitBtn) {
//PREVENT FORM SUBMITTION
this.preventDefault(evnt);
//IF INPUT HAS FOCUS
} else if (type === "focus") {
//RESET CLASSLIST
this.resetClassList(target.parentElement);
//RESET ERRORS
this.resetErrors(target);
return false;
}
//RESET CLASSLIST
this.resetClassList();
//CHECK FIELDS
this.checkFields();
},
preventDefault: function (evnt) {
//PREVENT DEFUALT
evnt.preventDefault();
},
checkFields: function () {
var i,
validCount = 0,
//EMAIL FILTER
filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
//CYLCE THROUGH INPUTS
for (i in this.fields) {
if (this.fields.hasOwnProperty(i)) {
input = this.fields[i];
//CHECK IF FIELD IS EMPTY
if (input.value === "") {
//ADD ERROR CLASS
this.addClass(input, classError);
//CHECK IF EMAIL IS VALID
} else if (i === "userEmail" && !filter.test(input.value)) {
//ADD ERROR CLASS
this.addClass(input, classError);
} else {
//FIELD IS VALID
this.addClass(input, classSuccess);
validCount += 1;
}
}
}
//IF ALL FEILDS ARE VALID
if (validCount === 3) {
//SUBMIT FORM
this.submitForm();
}
},
addClass: function (input, clss) {
container = input.parentElement;
//IF INPUT HAS ERROR
if (clss === classError) {
//SHOW ERROR MESSAGE
this.errorMessage(input);
}
//ADD CLASS
input.parentElement.classList.add(clss);
},
errorMessage: function (input) {
var message;
//IF USERNAME HAS ERROR
if (input === this.fields.userName) {
message = "Please enter your name";
//ELSE IF USEREMAIL HAS ERROR
} else if (input === this.fields.userEmail) {
message = "Please enter a valid email";
//ELSE IF USERMESSAGE HAS ERROR
} else if (input === this.fields.userMessage) {
message = "Please enter your feedback";
}
this.renderError(input, message);
},
renderError: function (input, message) {
var html;
//GET INPUT CONTAINER
container = input.parentElement;
//RENDER HTML
html = document.createElement("div");
html.setAttribute("class", "message");
html.innerHTML = message;
//IF MESSAGE ELEMENT DOESN'T EXIST
if (!container.getElementsByClassName("message")[0]) {
//INSERT MESSAGE TO INPUT CONTAINER
container.insertBefore(html, container.firstElementChild);
}
},
resetClassList: function (input) {
var i;
//IF TARGETING SPECIFIC INPUT
if (input) {
//GET INPUT CONTAINER
container = input.parentElement;
//REMOVE CLASSES
container.classList.remove(classError, classSuccess);
//FOCUS ON INPUT FIELD
input.focus();
} else {
for (i in this.fields) {
if (this.fields.hasOwnProperty(i)) {
//REMOVE CLASSES FROM ALL FIELDS
this.fields[i].parentElement.classList.remove(classError, classSuccess);
}
}
}
},
resetErrors: function (input) {
//GET INPUT CONTAINER
container = input.parentElement;
//IF CONTAINER CONTAINS ERROR
if (container.classList.contains(classError)) {
//RESET CLASSES
this.resetClassList(input);
}
},
submitForm: function () {
var waitForAnimation;
//ADD SUCCESS CLASS
this.contactForm.classList.add(classSuccess);
//WAIT FOR ANIMATION TO FINISH
this.changeHeader("Sent Succesfully");
//WAIT FOR ANIMATION TO FINISH
setTimeout(
this.changeHeader.bind(this, "Thank you for your feedback"),
1200
);
},
changeHeader: function (text) {
//CHANGE HEADER TEXT
this.formHeader.innerHTML = text;
}
};
//INITIATE FORM VALIDATOR
formValidator.init();
})();
Write this in first line of page directive in source code
<%# Page EnableEventValidation="false" %>
This code isn't doing anything when I submit the form. What am I doing wrong? In the HTML, an error message is shown or hidden based on a class.
I hope you can help me figure out this problem. Thanks in advance.
$(document).ready(function() {
function validateForm() {
var first_name = $("#first_name").value;
var last_name = $("#last_name").value;
var phone = $("#phone").value;
var email = $("#email").value;
var code = $("#vali_code").value;
var ssn = $("#ssn").value;
var income = $("#nm_income").value;
var error = $(this).find("span.error_txt").removeClass(".hidden").addClass(".show");
var emailReg = /^([w-.]+#([w-]+.)+[w-]{2,4})?$/;
if (first_name === "") {
error;
}
if (last_name === "") {
error;
}
if (email === "" || email !== emailReg) {
error;
}
if (phone === "" || phone < 9) {
error;
}
if (ssn === "" || ssn > 4) {
error;
}
if (income === "") {
error;
}
if (code === "") {
error;
}
return true;
}
});
If you call the function in inline event onsubmit you should add return keyword to the function call in your form inline event like :
<form onsubmit='return validateForm()'>
But I think the main problem comes from the .value in your code it should be replaced by .val() since the value isn't an attribute of jQuery objects.
My suggestion is to attach the submit event in the JS code like the snippet below.
NOTE: The argument passed toremoveClass() and addClass() methods shouldn't contains dot . at the start.
$(function() {
$('form').on('submit', validateForm);
})
function validateForm() {
var first_name = $("#first_name").val();
var last_name = $("#last_name").val();
$(this).find("span.error_txt").removeClass("hidden").addClass("show");
if (first_name === "") {
return false;
}
if (last_name === "") {
return false;
}
alert('Form will be submited.');
return true;
}
.hidden {
display: none;
}
.show {
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input id='first_name'><br>
<input id='last_name'><br>
<button>Submit</button>
<span class="error_txt hidden">Error occurred check you form fields again.</span>
</form>
You need to return false in case the form is invalid, otherwise it will be submitted.
I need to be able to require certain fields if someone selects a value of "Yes" from a dropdown. I've used the following code but it doesn't seem to work.
$(function () {
$('#anyAdditionalInc').keyup(function () {
if ($(this).val() == "No") {
$('#additionalIncomeSource').removeAttr('required');
$('#additionalIncomeAmt').removeAttr('required');
} else {
$('#additionalIncomeSource').attr('required', 'required');
$('#additionalIncomeAmt').attr('required', 'required');
}
});
});
My dropdown looks like this
<div class="form-group">#Html.LabelFor(m => m.anyAdditionalInc, new { #class = "col-sm-2 control-label" })
<div class="col-sm-10">
<div class="col-sm-4">#Html.DropDownListFor(m => m.anyAdditionalInc, new SelectList(new List
<Object>{ new { value = "", text = "----"}, new { value = "Yes", text = "Yes"}, new { value = "No", text = "No"}, }, "value", "text"), new { #class = "form-control", id = "anyAdditionalInc" }) #Html.ValidationMessageFor(m => m.anyAdditionalInc)</div>
</div>
</div>
Any help is appreciated. It doesnt seem to want to require the validation on the source and amt fields when selecting yes.
A dropdown (I guess you mean a <select> element by that) doesn't have much keyup events. Try change instead:
$(function () {
$('#anyAdditionalInc').change(function () {
var active = $(this).val() != "No"),
fields = $('#additionalIncomeSource, #additionalIncomeAmt');
fields.prop('required', active);
if (!active) fields.val("");
});
});
Even though #Bergi answered the question from a client-side perspective, since you tagged the question asp.net-mvc-4 I presume you may wish to know how it's done on the server side (where it really matters!):
You can simply check it in your controller:
public ActionResult Foo(SomeModel someModel) {
if (someModel.anyAdditionalInc != "Yes") {
ModelState.AddModelError("", "You must select yes");
}
}
Or if you want to push the logic into your model itself:
public class SomeModel: IValidatableObject {
public string anyAdditionalInc {get; set;}
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) {
if (this.anyAdditionalInc != "Yes") {
yield return new ValidationResult("You must select yes");
}
}
}
Notice how the model:
Implements IValidateableObject
Has a method named Validate which returns the type IEnumerable<ValidationResult>
During the model binding process this method will automatically be called and if a validation result is returned your ModelState will no longer be valid. So using this familiar code in your controller will make sure you don't take any action unless your custom conditions check out:
public class SomeController {
public ActionResult SomeAction() {
if (ModelState.IsValid) {
//Do your stuff!
}
}
}
Guys I'm new to JavaScript, so not sure where the error is. Basically I've two submit buttons in my cshtml. one with the id = email and other id = sms. I've set value=" ". I'm using these buttons in a form.
what I want to do is; by clicking on these button I want to pass them a value so that I can use that value in model and controller, like in switch statement. tried various ways but still its passing null value. please advise!
function GetVal() {
var input = document.getElementsByTagName('input');
for (i = 0; i < input.length; i++) {
if (input[i].type == 'submit') {
if (input[i].id == 'email') {
//input[i].value = 'submitEmail';
//input[i].setAttribute("value", "subEmail");
document.getElementById("email").setAttribute("subEmail", "value");
break;
}
}
}
}
<input id="email" type="submit" class="#( Model.UnsubscribedEmail == null ? "unsubscribe" : "subscribe")" onclick="GetVal();" />
Model
public static void susbscription(MyModel model, string submitButton)
{
switch (submitButton)
{
case "subEmail":
//Code here
break;
}
}
Controller
[HttpPost]
public ActionResult MarketingPreferences(MyModel model, string submitButton)
{
MarketingPreferencesModel.susbscription(model, submitButton);
return View(model);
}
Try this:
<input id="email" type="submit" name="submitButton" onclick="GetVal(this);" class="#( Model.UnsubscribedEmail == null ? "unsubscribe" : "subscribe")" />
In JavaScript:
function GetVal(element) {
element.value = "subEmail";
}
In Action:
public ActionResult MarketingPreferences(MyModel model, string submitButton)
{
MarketingPreferencesModel.susbscription(model, submitButton);
return View(model);
}
I am using MVC, not that this makes a difference, but I have a text box for searching.
<% using (Html.BeginForm("Index", "Search", FormMethod.Post)) { %>
<%= Html.AntiForgeryToken() %>
<div id="search_box">
<span id="search-title">Search Site</span>
<div>
<%= Html.TextBox("searchText", "type here, then press enter", new { #class = "search_input" }) %>
</div>
</div>
<% } %>
I used to have the onblur and onfocus events set on this text box to do some text swapping when the user clicked into it or out of it without typing anything. But, I moved them into a JS file because eventually, we want to add other functionality through JS, such as autocomplete, etc.
The problem with my JS is that it submits no matter what.
var searchHandler = function() {
var searchBox = "searchText";
var defaultText = "type here, then press enter";
var attachEvents = function() {
$("#" + searchBox).focus(function() {
if (this.value == defaultText) {
this.value = '';
}
}).blur(function() {
if (this.value == '') {
this.value = defaultText;
}
}).keyup(function(event) {
var searchTerms = $("#" + searchBox).val();
if (event.keyCode == 13 && searchTerms == '') {
return false;
}
else {
return true;
}
});
};
return {
init: function() {
$("#" + searchBox).val(defaultText)
attachEvents();
}
}
} ();
$().ready(function() {
searchHandler.init();
});
What I really need is to just make it so that enter does not submit the form if the textbox is empty. Any ideas?
If you use jQuery you can simply return a false if the validation rules are not met.
$(document).ready( function(){
$('form').submit(function(){
if( $('#searchText').val() == '')
return false;
else
return true; //just to be explicit, not really necessary.
});
});
Or something close to that.