javascript validation for name,contact numbers - asp.net

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="";
}

Related

Asp.Net validation check at client side

I am validating data at client side in asp.net validator by using following code snipet.
function ValidateData(){
if (!Page_ClientValidate("Validator1") || !Page_ClientValidate("Validator2")) {
return false;
}
else{
return true;
}
I called it on submit of button. But it showing validation messages of Validator1 group. Its not showing me validation messages of Validator2 group.
Just gone through :
see this link question , here its told - || operator short-circuits if the left condition is true.
Does a javascript if statement with multiple conditions test all of them?
If you want both , then cant you try like this :
function ValidateData(){
if (!Page_ClientValidate("Validator1"))
{
if (!Page_ClientValidate("Validator2"))
{
return false;
}
else
{
return false;
}
return false;
}
else
{
return true;
}
}
Just a random try , this code :)
Rigin

I want to block certain characters in javascript validation?

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 . .

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..)

Dropdownlist doesn't postback after Page_ClientValidate()

Update:
I have just found the solution. The following function works (remove the else part):
function confirmSubmit() {
if (Page_ClientValidate("Group1")) {
return window.confirm("Are you sure to submit the form?");
}
}
But I am wondering why it doesn't work when I add the else part.
Question:
I want to have a confirm dialog after user fills in all the data in the form.
I set onclientclick="return confirmSubmit()" in the submit button.
function confirmSubmit() {
if (Page_ClientValidate("Group1")) {
return window.confirm("Are you sure to submit the form?");
} else {
return false;
}
}
If Page_ClientValidate("Group1") returns false, the dropdownlist doesn't cause postback after I first select the item, and the postback only occurs when I select the dropdownlist second time.
What's the problem?
After Page_ClientValidate is called, the variable Page_BlockSubmit gets set to true, which blocks the autopost back. Page_BlockSubmit was getting reset to false on the second click, for what reasons I still don't fully understand. I'm looking more into this, but I have a solution and I'm under the gun so I'm rolling with it....
Just add below code in the code block which executes if Page is not valid.
Page_BlockSubmit = false;
e.g.
function ValidatePage()
{
flag = true;
if (typeof (Page_ClientValidate) == 'function')
{
Page_ClientValidate();
}
if (!Page_IsValid)
{
alert('All the * marked fields are mandatory.');
flag = false;
Page_BlockSubmit = false;
}
else
{
flag = confirm('Are you sure you have filled the form completely? Click OK to confirm or CANCEL to edit this form.');
}
return flag;
}
I have just found the solution. The following function works (remove the else part):
function confirmSubmit() {
if (Page_ClientValidate("Group1")) {
return window.confirm("Are you sure to submit the form?");
}
}

Resources