One Error Message Needed If 2 Fields Are Empty - javascript

I have an asp.net contact us form which has 'Tel No.' and 'Email' fields. What i'm after is one error message for if both these fields are blank when the form is submitted but i can't figure it out, brain fart i think lol
HTML
<div class="form-group">
<asp:Label ID="TelFieldLabel" class="col-md-3 control-label" runat="server" Text="Contact No." AssociatedControlID="TelField"></asp:Label>
<div class="col-md-3">
<asp:TextBox ID="TelField" runat="server" class="form-control" type="Number"></asp:TextBox>
</div>
</div>
<div class="form-group">
<asp:Label ID="EmailFieldLabel" class="col-md-3 control-label" runat="server" Text="Email address" AssociatedControlID="EmailField"></asp:Label>
<div class="col-md-3">
<asp:TextBox ID="EmailField" runat="server" class="form-control" type="Text"></asp:TextBox>
</div>
<div class="col-md-offset-3 col-md-9">
<asp:RegularExpressionValidator Display="Dynamic" runat="server" ID="RegularExpressionValidator1" SetFocusOnError="True" ForeColor="Red" ControlToValidate="EmailField" ErrorMessage="RegularExpressionValidator" ValidationExpression="\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*">Email address is not a valid format.</asp:RegularExpressionValidator>
<asp:CustomValidator id="CustomValidator2" runat="server" Display="Dynamic" ForeColor="Red" ErrorMessage="Please enter either a phone number of an email address." ClientValidationFunction="ContactFields_ClientValidate" OnServerValidate="PrefContact_ServerValidate" />
</div>
</div>
div class="form-group">
<div class="col-xs-12">
<div class="pull-right">
<asp:LinkButton ID="SubmitButton" runat="server" OnClick="SubmitButton_Click" CssClass="btn btn-primary" OnClientclick="ShowProcessingPopup();"><span class="glyphicon glyphicon-ok"></span> Submit</asp:LinkButton>
</div>
</div>
</div>
My email address also hase a validation error assigned to it as you can see from the abve.

ASP.NET way to do it is,
Markup
<asp:CustomValidator ID="CustomValidator2" runat="server"
Display="Dynamic"
ForeColor="Red"
ErrorMessage="Please enter either a phone number of an email address."
ClientValidationFunction="ContactFields_ClientValidate"
OnServerValidate="CustomValidator2_ServerValidate">
JavaScript
function ContactFields_ClientValidate(source, arguments) {
var telephoneField = document.getElementById("<%= TelField.ClientID %>");
var emailField = document.getElementById("<%= EmailField.ClientID %>");
if (telephoneField.value == "" && emailField.value == "") {
arguments.IsValid = false;
}
else {
arguments.IsValid = true;
}
}
Code-Behind
protected void CustomValidator2_ServerValidate(object source, ServerValidateEventArgs args)
{
if (TelField.Text.Trim() == "" && EmailField.Text.Trim() == "")
{
args.IsValid = false;
}
else
{
args.IsValid = true;
}
}

Related

ASP.NET JQuery unable to access Server and HTML Controls

I'm having problems with integrating JavaScript to ASP.NET. I want to use jQuery or even Vanilla JavaScript to do some client side operations but I'm unable to access HTML and ASP.NET Server Controls. I have tried many solution, just like using <%= element.ClientID %> but none worked for me. I'm unable to identify my fault, please help me identifiying.
Alread Tried:
RegisterClientScriptBlock
Include JavaScript File Directly
$("#<% element.ClientID %>")
document.getElementById("<%= element.ClientID %>");
Using HTML control instead Server & vice versa.
new_quiz.aspx
<%# Page Title="" Language="C#" MasterPageFile="~/teacher_quizes/teacher_quizes.master" AutoEventWireup="true" CodeBehind="new_quiz.aspx.cs" Inherits="onlineQuiz_bsef17m35.teacher_quizes.new_quiz" %>
<asp:Content ID="Content1" ContentPlaceHolderID="quizes" runat="server">
<div class="form p-2">
<div class="form-group p-1">
<asp:Label runat="server" Text="Quiz Title"></asp:Label><br />
<small class="text-danger">The title of your quiz</small>
<input runat="server" type="text" maxlength="64" id="title"
class="form-control"/>
<asp:RequiredFieldValidator runat="server" ControlToValidate="title"
ErrorMessage="Title is required"></asp:RequiredFieldValidator>
</div>
<div class="form-group p-1">
<asp:Label runat="server" Text="Quiz Description"></asp:Label><br />
<small class="text-danger">Please describe this quiz</small>
<textarea runat="server" id="description" class="form-control" rows="2"
maxlength="128">
</textarea>
<asp:RequiredFieldValidator runat="server" ControlToValidate="description"
ErrorMessage="Description is required" CssClass="text-warning text-muted">
</asp:RequiredFieldValidator>
</div>
<div class="form-group p-1">
<asp:Label runat="server" Text="Maximum Marks"></asp:Label><br />
<small class="text-danger">The maximum achiveable marks for this quiz, between 1 and 1000</small>
<input runat="server" type="number" min="1" max="100" id="maxMarks"
class="form-control"/>
<asp:RangeValidator MinimumValue="1" MaximumValue="1000"
runat="server" ControlToValidate="maxMarks" CssClass="text-warning"
ErrorMessage="Please choose a number between 1 and 100">
</asp:RangeValidator>
</div>
<div class="form-group p-1">
<asp:Label runat="server" Text="Passing Marks"></asp:Label><br />
<small class="text-danger">The passing marks for this quiz, between 1 and 1000 and lesser than or equal to total marks</small>
<input runat="server" type="number" min="1" max="100" id="passingMarks"
class="form-control"/>
<asp:RangeValidator MinimumValue="1" MaximumValue="1000"
runat="server" ControlToValidate="passingMarks" CssClass="text-warning"
ErrorMessage="Please choose a number between 1 and 100">
</asp:RangeValidator>
</div>
<div class="form-group p-1 card mb-2">
<div><b runat="server" id="questions">Quesions</b></div>
<div class="form-group">
<asp:Label runat="server" Text="Question"></asp:Label><br />
<asp:TextBox runat="server" ID="question" CssClass="form-control"/>
<asp:Label runat="server" Text="Type of Question"></asp:Label><br />
<select runat="server" id="questionType" class="form-control"
onchange="questionTypeChange()"></select>
<div runat="server" id="questionOptions">
<small>Please check checkbox in front of Options to denote an option as true</small>
<div class="form-group">
<asp:Label runat="server" Text="Option 1"></asp:Label><br />
<input runat="server" type="text" maxlength="64" id="questionOption1"
class="form-control" />
<input runat="server" type="checkbox" id="questionOption1Validity"
class="input-group-append"/>
<asp:RequiredFieldValidator runat="server" ControlToValidate="questionOption1"
ErrorMessage="Option 1 is required!" CssClass="text-danger">
</asp:RequiredFieldValidator>
</div>
<div class="form-group">
<asp:Label runat="server" Text="Option 1"></asp:Label><br />
<input runat="server" type="text" maxlength="64" id="questionOption2"
class="form-control" />
<input runat="server" type="checkbox" id="questionOption2Validity"
class="input-group-append"/>
<asp:RequiredFieldValidator runat="server" ControlToValidate="questionOption2"
ErrorMessage="Option 2 is required!" CssClass="text-danger">
</asp:RequiredFieldValidator>
</div>
<div class="d-flex flex-row-reverse">
<button class="btn btn-sm btn-primary">Add another Option</button>
</div>
</div>
</div>
</div>
</div>
</asp:Content>
new_quiz.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
namespace onlineQuiz_bsef17m35.teacher_quizes
{
public partial class new_quiz : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
return;
}
DatabaseEntities db = new DatabaseEntities();
var quizes = db.getQuestionTypes().ToArray();
questionType.DataSource = quizes;
questionType.DataBind();
if (questionType.Value == "Multiple Choice")
{
questionOptions.Visible = true;
} else
{
questionOptions.Visible = false;
}
/* register client scripts */
Type scriptType = this.GetType();
String scriptName = "script";
String scriptUrl = "./new_quiz.js";
String scriptText = File.ReadAllText(Server.MapPath(scriptUrl));
ClientScriptManager scriptManager = Page.ClientScript;
if (!scriptManager.IsClientScriptBlockRegistered(scriptType, scriptName))
{
scriptManager.RegisterClientScriptBlock(scriptType, scriptName, scriptText, true);
}
}
}
}
new_quiz.js
function questionTypeChange() {
const element = document.getElementById("<%= question.ClientID %>");
console.log(element);
}
First check if your jQuery is loaded correctly.
Open console (press F12) and type "jQuery" and enter - you should get something back. If you get "not defined" - then make sure you do load it.
Then, you should be able to access your HTML, via jQuery selector.
More info here: https://www.w3schools.com/jquery
Real problem was that I was using external script. ASP.NET Tag in external script does not work. For that I used jQuery pattern matching to find controls.
To find button with ID="saveButton", I used $("[id$=saveButton]") that results in all Controls having an ID ending with saveButton.
Above works, because ASP.NET appends original ID to some random ID generated while compilation, so final html id always ends with original id given in markup.

Disable A Button When asp:TextBox Empty & no asp:RadioButton Is Selected

I have an asp.net webform and i want my submit button to be disabled if my asp:TextBox is empty and also no selection has been made for my asp:RadioButton.
Currently i have the following for my field but i dont know how i can join this for the radio buttons
JQuery
$(document).ready(function ()
{
$("#MainContent_btnRemoveUser").prop('disabled', true);
$("#MainContent_btnAddUser").prop('disabled', true);
});
// Disables 'Remove' button unless all fields popluted
$("#MainContent_txtRemoveUser").on("change", function ()
{
if ($('#MainContent_txtUsername').val())
{
$("#MainContent_btnRemoveUser").prop('disabled', false);
}
else
{
$("#MainContent_btnRemoveUser").prop('disabled', true);
}
});
HTML
<div class="form-group">
<asp:Label runat="server" AssociatedControlID="txtRemoveUser" CssClass="col-sm-offset-2 col-sm-3 control-label">Enter Name To Be Removed</asp:Label>
<div class="col-sm-3">
<asp:TextBox runat="server" ID="txtRemoveUser" CssClass="form-control" />
</div>
</div>
<div class="form-group">
<asp:Label runat="server" CssClass="col-sm-offset-2 col-sm-3 control-label">
<b>Request For</b>
</asp:Label>
<div class="col-sm-3">
<label class="radio-inline">
<asp:RadioButton runat="server" ID="rbRemoveYourself" GroupName="RemoveRequestFor" /> Myself
</label>
<label class="radio-inline">
<asp:RadioButton runat="server" ID="rbRemoveOtherUser" GroupName="RemoveRequestFor" /> Other user
</label>
</div>
</div>
<div class="row">
<div class="col-sm-offset-8 col-sm-3" style="padding-left: 0px">
<asp:Button ID="btnRemoveUser" runat="server" Text="Remove From The List" CssClass="btn btn-danger" ToolTip="Click to remove the specified user from the payday lunch list." />
</div>
</div>
There you go! a new function has been added to disable the button and will be called on blur for text box and on change for radio buttons.
HTML
<div class="form-group">
<asp:Label runat="server" AssociatedControlID="txtRemoveUser" CssClass="col-sm-offset-2 col-sm-3 control-label">Enter Name To Be Removed</asp:Label>
<div class="col-sm-3">
<asp:TextBox runat="server" ID="txtRemoveUser" CssClass="form-control" />
</div>
</div>
<div class="form-group">
<asp:Label runat="server" CssClass="col-sm-offset-2 col-sm-3 control-label">
<b>Request For</b>
</asp:Label>
<div class="col-sm-3">
<label class="radio-inline">
<asp:RadioButton runat="server" ID="rbRemoveYourself" GroupName="RemoveRequestFor" /> Myself
</label>
<label class="radio-inline">
<asp:RadioButton runat="server" ID="rbRemoveOtherUser" GroupName="RemoveRequestFor" /> Other user
</label>
</div>
</div>
<div class="row">
<div class="col-sm-offset-8 col-sm-3" style="padding-left: 0px">
<asp:Button ID="btnRemoveUser" runat="server" Text="Remove From The List" CssClass="btn btn-danger" ToolTip="Click to remove the specified user from the payday lunch list." />
</div>
</div>
JavaScript
<script>
$(document).ready(function () {
$("#MainContent_btnRemoveUser").prop('disabled', true);
$("#MainContent_btnAddUser").prop('disabled', true);
});
$("#MainContent_txtRemoveUser").on("blur", function () {
disableButton();
});
$("#MainContent_rbRemoveYourself").change(function () {
disableButton();
});
$("#MainContent_rbRemoveOtherUser").change(function () {
disableButton();
});
// Disables 'Remove' button unless all fields popluted
function disableButton() {
var isRbRemoveSelfChecked = $("#MainContent_rbRemoveYourself").is(':checked')
var isRbRemoveOtherChecked = $("#MainContent_rbRemoveOtherUser").is(':checked')
if ($('#MainContent_txtRemoveUser').val() != '' && (isRbRemoveSelfChecked || isRbRemoveOtherChecked)) {
$("#MainContent_btnRemoveUser").prop('disabled', false);
}
else {
$("#MainContent_btnRemoveUser").prop('disabled', true);
}
}
</script>
This should give you the expected result:-
$('input[name="RemoveRequestFor"]').change(function () {
if($("#MainContent_txtUsername").val().trim() != "")
$("#MainContent_btnAddUser").prop('disabled', false);
});
$("#MainContent_txtUsername").blur(function () {
if($('input[name="RemoveRequestFor"]:checked').length > 0)
$("#MainContent_btnAddUser").prop('disabled', false);
});
Also, you can use keyup function instead of blur to make your form more responsive.
Try replacing if ($('#MainContent_txtUsername').val()) with
if ($('#MainContent_txtUsername').val() != '')
For radio button, don't check any condition on onchange and write same logic.

validation on a required field

working from the validation example:
http://www.w3schools.com/aspnet/showaspx.asp?filename=demo_validationsum
using asp.net I would like to display the error message 'You must enter a value in the following fields:' to include the field name that is wrong, when data is incorrectly entered.
so far the user cant continue until the correct data is entered and a red * appears beside the column. I would now like to add the error message.
<div id="floater_EditData_Panel_popup" title="Feature Information" class="floaterDiv">
Select a feature to view/edit feature information.
<p> </p>
<asp:UpdatePanel runat="server" id="UpdatePanelDetails1" updatemode="Conditional" Childrenastriggers="false">
<ContentTemplate>
<asp:PlaceHolder ID="PlaceHolder1" runat="server" >
</asp:PlaceHolder>
<br />
<br />
<div id="EditDataPanelMessageOutput" style="color:Red;">
<asp:ValidationSummary ID="ValidationSummary1"
HeaderText="You must enter a value in the following fields:"
DisplayMode="BulletList"
EnableClientScript="true"
runat="server"/>
</div>
<div id="FeatureMeasureOutput"></div>
<br />
<br />
<div class="buttonwrap">
<div id="Span2" class="ActionBtns" style="display: inline-block;" >
<asp:button runat="server" id="UpdateButton" value="Save" Text="Save" OnClientClick="ValidateEditData();" CausesValidation="true" ValidationGroup="g_currentSelectedLayerName" />
</div>
</div>
</ContentTemplate>
</asp:UpdatePanel>
</div>
function ValidateEditData() {
if (Page_ClientValidate(g_currentSelectedLayerName)) {
//alert('it is valid');
updateFeature();
return true;
}
else {
//alert('Data not valid');
return false;
}
}
Shouldnt the validation summary tag apply to the entire page?
How about:
<asp:ValidationSummary ID="ValidationSummary1"
HeaderText="You must enter a value in the following fields:"
DisplayMode="BulletList"
EnableClientScript="true"
ValidationGroup="g_currentSelectedLayerName"
runat="server"/>
<asp:TextBox ID="txtFirstName" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator runat="server" Display="Dynamic" ControlToValidate="txtFirstName" ErrorMessage="First Name is required" ValidationGroup="g_currentSelectedLayerName"></asp:RequiredFieldValidator>
<asp:Button runat="server" Text="Submit" ValidationGroup="g_currentSelectedLayerName" />
And then add an appSetting to your web.config:
<appSettings>
<add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />
</appSettings>

asp.net + Custom validator not validating

I am trying to use a customvalidator to validate a DIV form and then close it if there is no validation errors. Below is my code, I can't get my custom validator to work, when I click submit, nothing validates, not sure what's wrong. Please advice. Thanks.
function validateRedemptionDialog(src, args) {
var rDate = document.getElementById('<%=uitxtRedemptionDate.ClientID%>').value;
if (rDate == "") {
args.IsValid = false;
return;
}
args.IsValid = true;
}
function closeRedemptionDialog() {
$('#dialog_Active_Redemption_confirm').dialog('close');
}
<div id="dialog_Active_Redemption_confirm" style="display: none">
<div class="section_body">
<div class="section_body_content">
<div class="row">
<asp:Label runat="server" ID="uilblRedemptionDate" Text="<%$ Resources:MembersNContactsManagerResources, uigrdhdrTransDate %>"
CssClass="label">
</asp:Label>
<asp:TextBox ID="uitxtRedemptionDate" runat="server" CssClass="text DatePicker" Style="width: 120px;
margin-right: 2px;">
</asp:TextBox>
<asp:CustomValidator ID="ctvtxtCamDateEnd" runat="server" ClientValidationFunction="validateRedemptionDialog"
ControlToValidate="uitxtRedemptionDate" ErrorMessage='<img src="../Images/icons/error.png" style="vertical-align:middle"/> XXX!'
Font-Names="arial" Font-Size="X-Small" SetFocusOnError="True" Display="Dynamic" />
</div>
<div class="row">
<asp:Label runat="server" ID="uilblRedemptionAmountSpent" Text="<%$ Resources:MembersNContactsManagerResources, uilblRedemptionAmountSpent %>"
CssClass="label">
</asp:Label>
<asp:TextBox ID="uitxtRedemptionAmountSpent" runat="server" Style="width: 120px;">
</asp:TextBox>
</div>
<div class="row">
<ul class="inline" style="margin-left: 137px; padding: 3px;">
<li><span class="button grey_btn">
<%--Submit button--%>
<asp:Button ID="uibtnRedemption" runat="server" Text="<%$ Resources : MembersNContactsManagerResources, uilblSubmit %>" OnClientClick="javascript:closeRedemptionDialog();"/>
<span> </span> </span></li>
</ul>
</div>
</div>
</div>
</div>
The validator will not validate empty text with your current configuration.
Set ValidateEmptyText to true if you need it to fire even when the user has entered nothing.
A CustomValidator does not need to have a ControlToValidate. If you need to validate in any case, you should leave that property empty.

ASP Enable enter key

I have a login box that I need to have submitted when enter is pressed. Below you are going to find part of the code. Please any help would be appreciated.
<div class="box-login clearfix">
<div class="box-login-header">
<h3>
Registered Users</h3>
</div>
<div>
<asp:Label ID="LblMessage" runat="server" ForeColor="Red"></asp:Label>
<asp:RequiredFieldValidator ID="Rfv_LoginId" runat="server" ControlToValidate="TextLogInId"
ErrorMessage="Login Id is required" ValidationGroup="A" Display="Dynamic"></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="RevLoginId" runat="server" ControlToValidate="TextLogInId"
ErrorMessage="Login id does not contain spaces,double quotes or +><=';:,|/"
ValidationExpression="[^ "+><=':,|/]*$" ValidationGroup="A" Display="Dynamic"></asp:RegularExpressionValidator>
<asp:RequiredFieldValidator ID="Rfv_Password" runat="server" ControlToValidate="TextPassword"
ErrorMessage="Password is required" ValidationGroup="A" Display="Dynamic"></asp:RequiredFieldValidator>
<asp:CustomValidator ID="CvPassword" runat="server" ClientValidationFunction="ValidatePassword"
ControlToValidate="TextPassword" ErrorMessage="" Display="Dynamic"></asp:CustomValidator>
<asp:RegularExpressionValidator ID="RevPassword" runat="server" ControlToValidate="TextPassword"
ErrorMessage="Space is not allowed" ValidationExpression="[^ ]*$" ValidationGroup="A"
Display="Dynamic"></asp:RegularExpressionValidator>
<asp:Label ID="LblPassword" runat="server" ForeColor="#FF0066"></asp:Label>
</div>
<p>
Please enter your GoCCL.com Login ID & Password below</p>
<ul>
<li>
<label for="cloginid">
Login ID:</label>
<asp:TextBox ID="TextLogInId" runat="server" CssClass="text-box" MaxLength="16" onblur="ClearMessage()"></asp:TextBox>
</li>
<li>
<label for="cpassword">
Password:</label>
<asp:TextBox ID="TextPassword" runat="server" TextMode="Password" CssClass="text-box"
MaxLength="16" onblur="ClearMessage()"></asp:TextBox>
</li>
</ul>
<asp:LinkButton ID="btnForgotPassword" CssClass="forgot" runat="server" Text="Forgot your Login ID or Password?"
OnClick="btnForgotPassword_Click"></asp:LinkButton>
<asp:ImageButton ID="CmdLogin" CssClass="btn-login" OnClick="CmdLogin_OnClick" OnClientClick="ClearMessage()"
runat="server" ImageUrl="/stylesheets/bookccl/images/button/btn-login.gif" CausesValidation="true" />
<div class="box-login-fotter clearfix">
<p>
<strong>New to GoCCL? </strong>
<asp:LinkButton ID="btnRegistration" runat="server" Text="Register Now" CssClass="register-new"
OnClick="btnRegistration_Click"></asp:LinkButton>
to join the fun!</p>
</div>
</div>
You could wrap it in a Panel control and set the DefaultButton to the button you want invoked when pressing Enter. There are also other options explored here:
http://www.beansoftware.com/asp.net-tutorials/accept-enter-key.aspx

Categories