CustomValidator with Parameters - javascript

I'm validating a TextBox with a CustomValidator and JavaScript, passing it some paramaters:
<asp:CustomValidator ID="CustomValidator1" runat="server" SetFocusOnError="true" Display="Dynamic" ValidateEmptyText="true" ControlToValidate="tbFirstName" ClientValidationFunction="CVH.createFunction(notEmpty, 'tbFirstName','tbFirstNameRequired')"></asp:CustomValidator>
This is my JavaScript
var CVH = {
createFunction: function (validationFunction, extParamOne, extParamTwo) {
var originalFunction = validationFunction;
var extOne = extParamOne;
var extTwo = extParamTwo;
return function (src, args) {
return originalFunction(src, args, extOne, extTwo);
}
}
}
var CustomValidatorHelper = CVH;
function notEmpty(source, args, tbID, spID)
{
var textBoxId = document.getElementById(tbID);
var spanID = document.getElementById(spID);
if (textBoxId.Value == null || textBoxId.Value == "") {
textBoxId.IsValid = false;
textBoxId.className = "form-control redBorder"
spanID.className = "redText";
alert(textBoxId.getAttribute('value'));
}
else {
textBoxId.IsValid = true;
textBoxId.className = "form-control"
spanID.className = "";
alert(textBoxId.getAttribute('value'));
}
}
So notEmpty is being called correctly and it is receiving the values for tbID and spID.
Problem is, when I do enter data in the TextBox and the code is executed, I still get not value. As in textBoxId.Value is NULL even with data in the box.
The Texbox is set to Static:
<asp:TextBox ID="tbFirstName" runat="server" class="form-control" autocomplete="name" MaxLength="20" ClientIDMode="Static" />
And it's rendering correctly:
<input name="ctl00$MainContent$tbFirstName" type="text" maxlength="20" id="tbFirstName" class="form-control" autocomplete="name" />
Any suggestions as to why it can't read the data in the TextBox?

So the error was in trying to check the value of textbox directly as opposed of using args:
function notEmpty(source, args, tbID, spID)
{
var textBoxId = document.getElementById(tbID);
var spanID = document.getElementById(spID);
if (args.Value == "")
{
args.IsValid = false;
textBoxId.IsValid = false;
textBoxId.className = "form-control redBorder"
spanID.className = "redText";
}
else
{
args.IsValid = true;
textBoxId.IsValid = true;
textBoxId.className = "form-control"
spanID.className = "";
}
}
So the code is still the same, for exception of changing textbox.value for args.value.

Related

trying to clear value in textbox in javascript function

i am trying to put validation on a textbox onkeyup. Textbox should contain only 5 digit value and after decimal only upto 4 decimal places. eg,12345 ,12345.2345
if user enter value other than regex then the texbox should become blank and i want it to be done in function and this function should be generic so that any other can use this function
.Aspx
<input type="number" id='inpSurfIndN' value='' runat="server" onkeyup="isFloatNumber(this.value)" />
Script function
<script type="text/javascript">
function isFloatNumber(value) {
var regex = /^[0-9]\d{0,4}(\.\d{1,4})?%?$/
var regmatch = regex.test(value);
if (regmatch == null|| regmatch==false) {
alert("Please fil correct expression");
value = "";
return false;
}
return true;
}
</script>
function isFloatNumber(elem) {
var regex = /^[0-9]\d{0,4}(\.\d{1,4})?%?$/
var regmatch = regex.test(elem.value);
if (regmatch == null|| regmatch==false) {
alert("Please fil correct expression");
elem.value = "";
return false;
}
return true;
}
<input type="number" id='inpSurfIndN' value='' runat="server" onkeyup="isFloatNumber(this)" />
<input type="number" id='inpSurfIndN1' value='' runat="server" onkeyup="isFloatNumber(this)" />
<input type="number" id='inpSurfIndN2' value='' runat="server" onkeyup="isFloatNumber(this)" />
You can use above snippet which will work for n numbers of inputs.
Updating value = ""; doesn't update the UI element. You should access the UI Element object by passing this and update the value like this.value = " " else you should use the selectors like document.getElementbyId() to access those object like document.getElementbyId('inpSurfIndN').value = ""
One of way you can use below logic,
function isFloatNumber(obj) {
var regex = /^[0-9]\d{0,4}(\.\d{1,4})?%?$/
var regmatch = regex.test(obj.value);
if (regmatch == null || regmatch == false) {
alert("Please fil correct expression");
obj.value = "";
return false;
}
return true;
}
<input type="number" id='inpSurfIndN' value='' runat="server" onkeyup="isFloatNumber(this)" />
var n = document.getElementById("numPeople"),
r = document.getElementById("result");
n.addEventListener("keyup", function(e) {
var regex = /^[0-9]\d{0,4}(\.\d{1,4})?%?$/
var regmatch = regex.test(n.value);
if (regmatch == null|| regmatch==false) {
alert("Please fil correct expression");
n.value='';
return false;
}
}, false);
<input id="numPeople" type="number" min="0" value="" placeholder="Pick a number" />
You cannot access the value variable which is passed as a parameter, it doesnt reference to the value of the input box
Instead you can access the element and change the value like below:
function isFloatNumber(eve) {
var regex = /^[0-9]\d{0,4}(\.\d{1,4})?%?$/
var regmatch = regex.test(value);
if (regmatch == null|| regmatch==false) {
alert("Please fil correct expression");
var elem = eve.currentTarget;
elem.value = "";
return false;
}
return true;
}

Populate texbox value from url parameter using javascript?

I have the following script. After a user clicks submits I want to redirect the user to the same page and populate the drop down and input box with parameter values from the url. Unfortunately they are not populating once the redirect completes. I also need to strip off * from the FilterMultiValue parameter so that the textbox has the orginal value entered?
I've checked the parameter values using an alert function and that works?
<script type="text/javascript">
function getUrlParams() {
var paramMap = {};
if (location.search.length == 0) {
return paramMap;
}
var parts = location.search.substring(1).split("&");
for (var i = 0; i < parts.length; i ++) {
var component = parts[i].split("=");
paramMap [decodeURIComponent(component[0])] = decodeURIComponent(component[1]);
}
return paramMap;
}
function RedirectUrl() {
var tb = document.getElementById("tbSearch").value;
var cs = document.getElementById("sfield").value;
var url = "";
if (tb != "") {
url = "FilterName=" + cs + "&FilterMultiValue=*" + tb + "*";
window.location.href = "mypage.aspx?" + url;
var params = getUrlParams();
alert(params.FilterName);
document.getElementById("sfield").value = params.FilterName;
document.getElementById('tbSearch').value = params.FilterMultiValue;
}
else {
return false;
}
}
function ClearUrl() {
window.location.href = "mypage.aspx";
document.getElementById("sfield").value = "";
document.getElementById('tbSearch').value = "";
}
</script>
Search Field:
<select id="sfield">
<option selected value="Title" >Title</option>
<option value="Body">Body</option>
</select>
Search Text:
<input type="text" id="tbSearch" />
<input type="button" id="btnSearch" value="Search" onclick="return RedirectUrl();" />
<input type="button" id="btnClear" value="Clear" onclick="return ClearUrl();" />
window.location.href = "mypage.aspx?" + url;
reloads the page, which will result in all code after that not beeing executed.
What you want to do is to add code for pageload and check if the parameters are given, then populate the textbox.
Something like:
window.addEventListener('load', function(){
var params = getUrlParams();
if(typeof params.FilterName !== 'undefined'){
// removes the first and the last char from the string
var t = params.FilterMultiValue.substr(1, params.FilterMultiValue.length-2);
document.getElementById("sfield").value = params.FilterName;
document.getElementById('tbSearch').value = t;
}
});

How can I set a variable to a text input and then make it appear on screen

I am making a text based game for school and I am stuck with trying to set a variable as an text input. What I would like to happen is the player type start into the input and it do what is inside of the if statement. However from there I would like the player to enter a username and then it set the variable of "name" to what they input but with out it saving the name as "start".
//js
var name = "";
var beginBeenTo = false;
if (beginBeenTo == false) {
if (input == "START") {
beginBeenTo = true;
page = page + 1;
healthPoints = 25;
soundEveningBreeze.play();
$("#welcome_message").show().insertBefore("#placeholder").delay(3000).fadeOut(3000);
$("<br><p class='text'>You there, what is your name?</p>").hide().insertBefore("#placeholder").delay(7000).fadeIn(3000);
if (input != "" || namingBeenTo == false) {
name = input;
}
}
}
document.getElementById("print_name").innerHTML = name;
Quite simply, watch for some event (keyup in my case), check if the input value is START, if so ask for a username.
var started = false;
var username = '';
$('input').on('keyup', function(){
var tmpValue = $(this).val();
if(started){
username = tmpValue
}
if(tmpValue === 'START') {
started = true;
$(this).val('')
$(this).attr('placeholder','Username')
}
$('#username').text(username)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<span id="username"></span>
<br>
<input type="text" placeholder="Type START to play">
it could be done with use of function like this :
var name = "";
$("form").submit(function() {
var input = $("#command_input").val().toUpperCase();
if (input == "START") {
name = $("#input_form").val();
}
}
document.getElementById("print_name").innerHTML = name;
you were missing one of #(hashtag)
And this code would work
Thanks & Cheers

Dynamic Validation of ASP.NET controls using Javascript/Jquery

I have multiple controls that need validation based on one condition: if one of the three controls have values, the fourth one must also contain a value. I have 4 sets of 4 controls, each numbered from one to four. I've written a quick and dirty function for validation, but it the code itself is unholy and defies most of the principal of good code design, its really ugly.
JavaScript Validation
$(document).ready(function () {
$("#<%= submitBtn.ClientID%>").click(function () {
var errorMessage = "";
var error = false;
var firstname1 = document.getElementById("<%=child1FN.ClientID%>").value;
var surname1 = document.getElementById("<%=child1LN.ClientID%>").value;
var relation1 = document.getElementById("<%=ddlRelationship1.ClientID%>").value;
var dob1 = document.getElementById("<%=DoB1.ClientID%>");
if ((firstname1 != "" || surname1 != "" || relation1 != "") && dob1.value == "") {
errorMessage += "First DoB needs to be filled. \n";
error=true;
}
var firstname2 = document.getElementById("<%=child2FN.ClientID%>").value;
var surname2 = document.getElementById("<%=child2LN.ClientID%>").value;
var relation2 = document.getElementById("<%=ddlRelationship2.ClientID%>").value;
var dob2 = document.getElementById("<%=DoB2.ClientID%>");
if ((firstname2 != "" || surname2 != "" || relation2 != "") && dob2.value == "") {
errorMessage += "Second DoB needs to be filled. \n";
error=true;
}
var firstname3 = document.getElementById("<%=child3FN.ClientID%>").value;
var surname3 = document.getElementById("<%=child3LN.ClientID%>").value;
var relation3 = document.getElementById("<%=ddlRelationship3.ClientID%>").value;
var dob3 = document.getElementById("<%=Dob3.ClientID%>");
if ((firstname3 != "" || surname3 != "" || relation3 != "") && dob3.value == "") {
errorMessage += "Third DoB needs to be filled. \n";
error=true;
}
var firstname4 = document.getElementById("<%=child4FN.ClientID%>").value;
var surname4 = document.getElementById("<%=child4LN.ClientID%>").value;
var relation4 = document.getElementById("<%=ddlRelationship4.ClientID%>").value;
var dob4 = document.getElementById("<%=DoB4.ClientID%>");
if ((firstname4 != "" || surname4 != "" || relation4 != "") && dob4.value == "") {
errorMessage += "Fourth DoB needs to be filled. \n";
error=true;
}
if (error) {
alert(errorMessage);
return false;
}
});
});
The problem is, that I cannot use a for loop as asp doesn't accept a javascript value for the following source
<tr>
<th>
Child one:
</th>
</tr>
<tr>
<td>
<asp:TextBox ID="child1FN" runat="server" />
</td>
<td>
<asp:TextBox ID="child1LN" runat="server" />
</td>
<td>
<asp:DropDownList ID="ddlRelationship1" runat="server" ></asp:DropDownList>
</td>
<td>
<telerik:RadDatePicker ID="DoB1" runat="server" Culture="English (Australia)" MinDate="1 Jan 1920" class="datePickerDOB">
</telerik:RadDatePicker>
</td>
</tr>
<tr>
<th>
Child two:
</th>
</tr>
<tr>
<td>
<asp:TextBox ID="child2FN" runat="server" />
</td>
<td>
<asp:TextBox ID="child2LN" runat="server" />
<td>
<asp:DropDownList ID="ddlRelationship2" runat="server"></asp:DropDownList>
</td>
<td>
<telerik:RadDatePicker ID="DoB2" runat="server" Culture="English (Australia)" MinDate="1 Jan 1920" class="datePickerDOB">
</telerik:RadDatePicker>
</td>
</tr> . . .
I've only shown the first two rows of the source which has been simplified and removed styling tags for legibility. Like I wrote; there's 4 rows and they're similar to the above code but with just a different ID.
I was wondering if anybody had any suggestions to improve this code?
Rendered Telerick Code
<span class="riSingle RadInput RadInput_MetroTouch" id="ctl00_cphBody_DoB1_dateInput_wrapper" style="width: 100%; display: block;">
<input name="ctl00$cphBody$DoB1$dateInput" class="riTextBox riEnabled" id="ctl00_cphBody_DoB1_dateInput" style="padding-left: 2px; font-size: 12px;" type="text">
<input name="ctl00_cphBody_DoB1_dateInput_ClientState" id="ctl00_cphBody_DoB1_dateInput_ClientState" type="hidden" value='{"enabled":true,"emptyMessage":"","validationText":"","valueAsString":"","minDateStr":"20202020-JanJan-0101-0000-0101-0000","maxDateStr":"99999999-DecDec-3131-0000-1212-0000","lastSetTextBoxValue":""}' autocomplete="off">
</span>
Giv the container an ID, this will make your life easier with jQuery (and is a little more efficient than using classes etc as selectors). Also, add a class to your "data" rows
<table id="formElements">
<tr><th>Child 1</th></tr>
<tr class="data"><!-- Form Elelemt Cells --></tr>
<!-- etc -->
</table>
Javascript
$(document).ready(function () {
var formTable = $("#formElements");
/*console.log(formTable); */
$("#submitBtn").click(function (index) {
var errorMessage = "";
var error = false;
//Use the fact we have the elements in a row to our advantage
$(formTable).find("tr.data").each(function (index) {
var firstName = $(this).find("td:nth-child(1) input").val();
var lastName = $(this).find("td:nth-child(2) input").val();
var relationship = $(this).find("td:nth-child(3) select").val();
//Taking a punt the value is in the hidden form field for DOB;
var dob = $(this).find("td:nth-child(4) input[type='hidden']").val();
//Use console to try and work out what telrik uses to hold the data
console.log($(this).find("td:nth-child(4) input[type='hidden']"));
console.log($(this).find("td:nth-child(4) input[type='text']"));
if ((firstName != "" || lastName != "" || relationship != "") && dob == "") {
errorMessage += "DoB " + (index + 1) + " needs to be filled. \n";
error = true;
}
});
if (error) {
alert(errorMessage);
return false;
}
});
});
This is a little quick and dirty and handling the telrick control could be tricky.
Demo
If you can use ASP.net inbuild validators to validate the telrik control you may be better off using them. Even stil, using a custom ASP.net validator should work in a similar fasion.
Update
I've added a couple of debug lines using console.log to try and help with the telrik controls.
Slighly hacky version
Keep the HTML as per above.
Javascript
$(document).ready(function () {
var formTable = $("#formElements");
/*console.log(formTable); */
//Create an array of the DatePicker controls
//You could replace the jQuery selectro with:
//document.getElementById("<%=DoB1.ClientID%>")
var arrDoB = new Array(
$("#<%=DoB1.ClientID%>"),
$("#<%=DoB2.ClientID%>"),
$("#<%=DoB3.ClientID%>"),
$("#<%=DoB4.ClientID%>")
);
$("#submitBtn").click(function (index) {
var errorMessage = "";
var error = false;
//Use the fact we have the elements in a row to our advantage
$(formTable).find("tr.data").each(function (index) {
var firstName = $(this).find("td:nth-child(1) input").val();
var lastName = $(this).find("td:nth-child(2) input").val();
var relationship = $(this).find("td:nth-child(3) select").val();
//Get the value of the datepicker control from the array
var dob = arrDoB[index].value;
if ((firstName != "" || lastName != "" || relationship != "") && dob == "") {
errorMessage += "DoB " + (index + 1) + " needs to be filled. \n";
error = true;
}
});
if (error) {
alert(errorMessage);
return false;
}
});
});

JavaScript / jQuery setting a content to <div> not sticking after postback

This is my code:
<asp:Button ID="btnSave" runat="server" OnClick="Save" CssClass="StylizedButton" resourcekey="btnSave" />
<div id="lbltot"></div>
JavaScript code:
$(document).ready(function() {
$("#<%= btnSave.ClientID %>").click(function() {
var functionReturn = true;
var focusElement = null;
var tot = $("<%= lblTotal.ClientID %>").val();
var txt1 = $("<%= txt1.ClientID %>").val();
var txt2 = $("<%= txt2.ClientID %>").val();
var txt3 = $("<%= txt3.ClientID %>").val();
var txt4 = $("<%= txt4.ClientID %>").val();
var cal = parseInt(txt1) + parseInt(txt2) + parseInt(txt3) + parseInt(txt4);
if (cal == 100)
{ return true; }
else {
$("lbltot").html("Total must be equal to 100%");
focusElement = tot;
functionReturn = false;
}
});
});
On the client side validation, I have to check the value of the TextBox, and the total should be equal to 100. If true, I should allow it to execute. If not, I need to throw an error stating the total should be 100.
What happens is that, after triggering the submit button, it show the text message only until the postback, and then it disappears. This part:
else {
$("lbltot").html("Total must be equal to 100%");
focusElement = tot;
functionReturn = false;
}
Is there any better way to display the error that persist?
You should return that functionReturn so that the submit action won't happen

Categories