I want to block certain characters in javascript validation? - asp.net

I want to block ][#{}'". But somehow I'm not able to put it in my code. What should I declare in place of val. Also when I put val = /^[0-9]+$/;. It blocks numbers when I put them alone. But when I concatenate a number with an alphabet, it gets accepted. For ex- abc123 gets accepted whereas 123 does not.
function Allvalidate()
{
var input;
var controlId = document.getElementById("<%=TextBox1.ClientID %>");
input = controlId.value;
var val = //????//
if (input == "")
{
alert("Please Enter a Value" + "\n");
return false;
}
else if (val.test(input))
{
alert("It does not accept these characters" + "\n");
return false;
}
else
{
return true;
}
}
</script>

$(document).keydown(function (e) {
if (e.which == [here you can write the key code of the characters that you want allow]) {
// TO DO Your Logic
}
});
Here I have used e.which and e.keycode because of browser compatibility [ firefox and IE may give the different code]
I hope this will work . .

Related

Hiding fields in Quick View form with JS not working

I need to hide few fields in a Quick View Form based on an Option Set (Choice) selection in that Quick View form. However it is not working, so am sharing the code I used for the same here. In my code, I am trying to hide certain fields if the option selected is not equal to a particular value...
function hideFields(executionContext) {
var formContext = executionContext.getFormContext();
var quickViewControl = formContext.ui.quickForms.get("General");
if (quickViewControl != undefined) {
if (quickViewControl.isLoaded()) {
var orgtypevalue = quickViewControl.getControl("new_organizationtype").getValue();
if (orgtypevalue != 248870006) {
quickViewControl.getControl("new_recipienttype").setVisible(false);
quickViewControl.getControl("new_businesstype").setVisible(false);
quickViewControl.getControl("new_businesstypecode").setVisible(false);
quickViewControl.getControl("new_businesstypecharacteristicstypecode").setVisible(false);
return;
}
else {
// Wait for some time and check again
setTimeout(getAttributeValue, 10, executionContext);
}
}
else {
console.log("No data to display in the quick view control.");
return;
}
else {
quickViewControl.getControl("new_recipienttype").setVisible(true);
quickViewControl.getControl("new_businesstype").setVisible(true);
quickViewControl.getControl("new_businesstypecode").setVisible(true);
quickViewControl.getControl("new_businesstypecharacteristicstypecode").setVisible(true);
return;
}
}
}
I need to know where am I wrong. Any help will be appreciated.
Thanks!
you need to update the following
first if version 9 I am updating this
"var quickViewControl = formContext.ui.quickForms.get("General");"
to "var quickViewControl = formContext._ui._quickForms.get("General");"
&
"var orgtypevalue = quickViewControl.getControl("new_organizationtype").getValue();"
to
"var orgtypevalue = quickViewControl.getAttribute("new_organizationtype").getValue();"
& update else with message to wait and call the function again like this
"setTimeout(hideFields, 10, executionContext);"
and add else for the If of "quickViewControl != undefined"
Kindly find the updated code:
function hideFields(executionContext) {
var formContext = executionContext.getFormContext();
var quickViewControl = formContext._ui._quickForms.get("General");
if (quickViewControl != undefined) {
if (quickViewControl.isLoaded()) {
var orgtypevalue = quickViewControl.getAttribute("new_organizationtype").getValue();
if (orgtypevalue != 248870006) {
quickViewControl.getControl("new_recipienttype").setVisible(false);
quickViewControl.getControl("new_businesstype").setVisible(false);
quickViewControl.getControl("new_businesstypecode").setVisible(false);
quickViewControl.getControl("new_businesstypecharacteristicstypecode").setVisible(false);
return;
}
else {
// Wait for some time and check again
setTimeout(hideFields, 10, executionContext);
}
}
else {
//console.log("No data to display in the quick view control.");
//return;
setTimeout(hideFields, 10, executionContext);
}
}
}

javascript validation for name,contact numbers

I have created 2 pages login and signup..On signup form I have used javascript for nonempty fields. Now I want to add validation for characters only, digits and date.
How to write these additional validations in my function. Please help. My code is:
<script type="text/javascript">
function Validateform() {
var Firstname = document.getElementById("txtfirst").value;
if (Firstname == "First Name" || Firstname == ""){
alert("Firstname must be filled out");
return false;
}
}
</script>
and I have called this function on onClientClick event of signup button.
Code to check alpha characters:
function onlyAlpha(inputtext){
var acceptedChars= /^[A-Za-z]+$/;
if(inputtext.value.match(acceptedChars)){
alert('ok');
return true;
} else {
alert('input alphabet characters only');
return false;
}
}
you can call this function on onblur on onClick with inputtext parameter as u wish to validate and the same way u can apply digits validation too.
There are n number of methods to validate name. Let me share my view
Method 1
First Name:
lname=document.getElementById('lname').value;
namelen=/^([a-zA-Z0-9]{5,15})+$/;
if(!namelen.test(lname))
{
alert('Enter a name');
return false;
}
else
{
document.getElementById('splname').innerHTML="";
}
returnValue;
}
Method 2 - To color the background
namelen=document.getElementById('lname').value.length;
lname=document.getElementById('lname').value;
if((namelen=<5 || namelen >=12) || !isNaN(lname))
{
document.getElementById('splname').innerHTML="Enter a name";
document.getElementById('lname').style.background="red";
document.getElementById('lname').focus();
}
else
{
document.getElementById('splname').innerHTML="";
document.getElementById('lname').style.background="green";
}
returnValue;
}
Method 3
fname=document.getElementById('fname').value;
namelen=/^([a-zA-Z0-9]{5,15})+$/;
if(!namelen.test(fname))
{
document.getElementById('spfname').innerHTML="Enter a name";
return false;
}
else
{
document.getElementById('spfname').innerHTML="";
}

Why does R# tell me, "Not all code paths return a value" in a click handler?

At the end of my submit button click handler, Resharper warns that, "Not all code paths return a value."
What value would it be expecting from an event handler?
In deference to full disclosure, this is that event handler:
$("#submit_button").click(function() {
// http://stackoverflow.com/questions/18192288/how-can-i-compare-date-time-values-using-the-jqueryui-datepicker-and-html5-time
var begD = $.datepicker.parseDate('mm/dd/yy', $('#BeginDate').val());
var endD = $.datepicker.parseDate('mm/dd/yy', $('#EndDate').val());
if (begD > endD) {
alert('Begin date must be before End date');
$('#BeginDate').focus();
return false;
}
else if (begD.toString() == endD.toString()) {
var dteString = begD.getFullYear() + "/" + (begD.getMonth() + 1) + "/" + begD.getDate();
var begT = new Date(dteString + " " + $('#BeginTime').val());
var endT = new Date(dteString + " " + $('#EndTime').val());
if (begT > endT) {
alert('Begin date must be before End date');
$('#BeginTime').focus();
return false;
}
}
$("#NumberOfResults").css("visibility", "visible");
$("#NumberOfResults").html("Please wait...");
EnableButton("submit_button", false);
// If all are selected, don't enumerate them; just set it at "All" (change of case shows that the logic did execute)
var deptsList = $('#depts').checkedBoxes();
if (deptsList.length < deptsArray.length) {
$('#deptHeader span').html(deptsList.join(", "));
}
else if (deptsList.length == deptsArray.length) {
$('#deptHeader span').html("All");
}
// " "
var sitesList = $('#sites').checkedBoxes();
$('#sitesHeader span').html(sitesList.join(", "));
if (sitesList.length < sitesArray.length) {
$('#sitesHeader span').html(sitesList.join(", "));
}
else if (sitesList.length == sitesArray.length) {
$('#sitesHeader span').html("All");
}
$('#hiddenDepts').val(deptsList);
$('#hiddenSites').val(sitesList);
var UPCs = $('#UPC').val();
if (UPCs == "All") {
$('#UPC').val("1"); // take everything (1 and greater)
}
var resultsText = jQuery.trim($("#spanNumberOfResults").text());
if (resultsText != "") {
$("#NumberOfResults").css("visibility", "visible");
if (resultsText == "0") {
$("#NumberOfResults").css("color", "red");
} else {
var href = '/#ConfigurationManager.AppSettings["ThisApp"]/CCRCriteria/LoadReport';
// report_parms (sic) is referenced from LoadReport
var report_parms = {
GUID: "#Model.GUID",
SerialNumber: "#Model.SerialNumber",
ReportName: "#Model.ReportName"
};
window.open(href, "report_window", "resizable=1, width=850, left=" + (screen.width / 2 - 425));
}
}
}); // end of submit button click
Resharper isn't aware of event handlers.
It sees that your function will sometimes return false and sometimes won't return anything, and it complains.
It doesn't realize that this pattern is perfectly fine for event handlers.
Ignore it. Click handlers "can" return a boolean value indicating whether to process the click normally (true) or ignore it (false).
Resharper sees any return in the function as a clue that it should always return something.

Getting control id within javascript

I have created my own code to provide date masking and validation for TextBox control in asp.net. Below is the code. The code works perfectly.
function IsValidDate(ctrlID)
{
var validDate=true;
var myT=document.getElementById("ctl00_ContentPlaceHolder1_CandidateResume1_TabContainer1_TabPanel2_Education1_"+ctrlID);
var mm=myT.value.substring(0,2);
var dd=myT.value.substring(5,3);
var yy=myT.value.substring(6);
if(mm!=0 && mm>12){
myT.value=""; validDate=false;
}
else
{
if((yy % 4 == 0 && yy % 100 != 0) || yy % 400 == 0)
{
if(mm==2 && dd>29){
myT.value=""; validDate=false;
}
}
else
{
if(mm==2 && dd>28){
myT.value=""; validDate=false;
}
else
{
if(dd!=0 && dd>31){
myT.value=""; validDate=false;
}
else
{
if((mm==4 || mm==6 || mm==9 || mm==11) && (dd!=0 && dd>30)){
myT.value=""; validDate=false;
}
}
}
}
}
if(validDate==false)
{
myT.style.backgroundColor='#FF0000';
myT.focus;
}
else
myT.style.backgroundColor='#FFFFFF';
}
function maskDate(ctrlID)
{
var myT=document.getElementById("ctl00_ContentPlaceHolder1_CandidateResume1_TabContainer1_TabPanel2_Education1_"+ctrlID);
var KeyID = (window.event) ? window.event.keyCode : 0;
if((KeyID>=48 && KeyID<=57) || KeyID==8)
{
if(KeyID==8)
return;
if(myT.value.length==2)
{
myT.value=myT.value+"/";
}
if(myT.value.length==5)
{
myT.value=myT.value+"/";
}
}
else
{
window.event.keyCode=0;
}
}
The problem -
I am attaching these functions to the textbox as -
TextBox1.Attributes.Add("onFocusout","IsValidDate('TextBox1');");
TextBox1.Attributes.Add("onKeyPress","maskDate('TextBox1');");
If you look at the javascript code I have collected the control id in myT variable. I have also passed the id of textbox while attaching the js functions using Attributes.Add()
My problem is that i dont want to pass the id of the textbox as i am already attaching it. That is i want to write the code as
TextBox1.Attributes.Add("onFocusout","IsValidDate();");
TextBox1.Attributes.Add("onKeyPress","maskDate();");
My question is how can i get the id of textbox to which i have attached these functions witin JS code.
NOTE: I DONT WANT TO PASS CONTROL NAME OR CONTROLS CLIENTID WHILE ADDING ATTRIBUTES. PLEASE NOTE THAT I WANT TO REPLACE
TextBox1.Attributes.Add("onFocusout","IsValidDate('TextBox1');");
WITH
TextBox1.Attributes.Add("onFocusout","IsValidDate();");
I WANT TO ATTACH THESE FUNCTIONS WITH MULTIPLE TEXTBOXES.
AS I AM USING .Attributes.Add(...) I WANT TO GET THE SAME CONTROLS CLIENTID WITHIN JS CODE.
Your help is highly appreciated.
Thanks and Regards
Mohammad Irfan
var txtControl = document.getElementById("<%= txtControl.ClientID %>");
Control.ClientID
Either pass TextBox1.ClientID to the function, or change the function call to be IsValidDate(this.id). But as you don't want to pass these in, you can place the TextBox1.ClientID in your javascript or use jquery to find it using $('[id*=TextBox1]').

How to combine similar JavaScript methods to one

I have an ASP.NET code-behind page linking several checkboxes to JavaScript methods. I want to make only one JavaScript method to handle them all since they are the same logic, how would I do this?
Code behind page load:
checkBoxShowPrices.Attributes.Add("onclick", "return checkBoxShowPrices_click(event);");
checkBoxShowInventory.Attributes.Add("onclick", "return checkBoxShowInventory_click(event);");
ASPX page JavaScript; obviously they all do the same thing for their assigned checkbox, but I'm thinking this can be reduced to one method:
function checkBoxShowPrices_click(e) {
if (_hasChanged) {
confirm(
'All changes will be lost. Do you wish to continue?',
function(arg) {
if (arg.toUpperCase() == 'YES') {
var checkBox = document.getElementById('<%=checkBoxShowPrices.UniqueID%
>');
checkBox.checked = !checkBox.checked;
eval("<%=base.GetPostBackEventReference(checkBoxShowPrices)%>");
_hasChanged = false;
}
});
return false;
} else {
eval("<%=base.GetPostBackEventReference(checkBoxShowPrices)%>");
}
}
function checkBoxShowInventory_click(e) {
if (_hasChanged) {
confirm(
'All changes will be lost. Do you wish to continue?',
function(arg) {
if (arg.toUpperCase() == 'YES') {
var checkBox = document.getElementById('<%
=checkBoxShowInventory.UniqueID%>');
checkBox.checked = !checkBox.checked;
eval("<%=base.GetPostBackEventReference(checkBoxShowInventory)%>");
_hasChanged = false;
}
});
return false;
} else {
eval("<%=base.GetPostBackEventReference(checkBoxShowInventory)%>");
}
}
Add to the event the checkbox that is raising it:
checkBoxShoPrices.Attributes.Add("onclick", "return checkBox_click(this, event);");
Afterwards in the function you declare it like this:
function checkBoxShowPrices_click(checkbox, e){ ...}
and you have in checkbox the instance you need
You can always write a function that returns a function:
function genF(x, y) {
return function(z) { return x+y*z; };
};
var f1 = genF(1,2);
var f2 = genF(2,3);
f1(5);
f2(5);
That might help in your case, I think. (Your code-paste is hard to read..)

Resources