How to prevent textbox from copying letters into that? - c#

I am currently working on a C# MVC project. While entering user details into database I need to customize my MobilePhone field to only accept numbers. After some searching I found the below code :
$(document).on("keypress","#MobilePhone", function (e) {
var regex = new RegExp("^[0-9]\d*$");
var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
if (regex.test(str)) {
return true;
}
e.preventDefault();
return false;
});
This code works for me, It only allows numbers to be entered in the Textbox.
But there is a problem, If a user copy some text and then paste the content in the Textbox nothing happens. Then if I press submitt button it submits and occur error.
So then I found this question :Disable Copy or Paste action for text box?
Answer to the question is :
$('#email').bind("cut copy paste",function(e) {
e.preventDefault();
});
But after I tried this I can not copy even numbers to the textbox. Is there any way I can prevent copying of alphabets and special characters only.

Just add some checks in your binding to prevent cut / copy / paste a non-number : https://jsfiddle.net/hswtutd9/
$(function() {
$("#email").bind("cut copy paste", function(e) {
const data = e.originalEvent.clipboardData.getData("Text")
if(! /\d./.test(data)) {
e.preventDefault()
}
})
})

why are you using text as your input type ????
if you are using strongly typed view ie editor for then just use data annotation
[DataType(DataType.PhoneNumber)]
public string PhoneNumber{get;set;} //i've used string here believing you initially made it as string and hence not effecting the code elsewhere
if you are using html inputs try
input type ="tel" note some brawser does not support tel for them i would prefer number

You can put the phone number validation code in a function and call if both places like:
function IsValidPhoneNumber(number) {
var regex = new RegExp("^[0-9]\d*$");
if (regex.test(number)) {
return true;
}
return false;
}
and now you can call it both places like:
$(document).on("keypress","#MobilePhone", function (e) {
if(!IsValidPhoneNumber($(this).val())) {
e.preventDefault();
return false;
}
}
$('#MobilePhone').bind("cut copy paste",function(e) {
if(!IsValidPhoneNumber($(this).val())) {
e.preventDefault();
return false;
}
});
or more better would be in a single event:
$(document).on("cut copy paste keypress","#MobilePhone", function (e) {
if(!IsValidPhoneNumber($(this).val())) {
e.preventDefault();
return false;
}
}
Now it would allow copying if the value satisfies the regular expression, you might need to tweak the function to check the whole number but this should give you idea how you can allow it there.
Hope it helped!

Related

how to validate selectize dropdownlist in mvc 4.5?

I am working with mvc in framework-4.5. In all other fields validation is working properly, but i am finding it difficult for selectize dropdownlist. Validation is working properly in simple dropdownlist also.
I tried to show message using field-validation-error and input-validation-error but not getting any success. Here are some changes i made in jquery.validate.unobtrusive.js.
function onError(error, inputElement) { // 'this' is the form element
var container = $(this).find("[data-valmsg-for='" + escapeAttributeValue(inputElement[0].name) + "']"),
replaceAttrValue = container.attr("data-valmsg-replace"),
replace = replaceAttrValue ? $.parseJSON(replaceAttrValue) !== false : null;
container.removeClass("field-validation-valid").addClass("field-validation-error");
error.data("unobtrusiveContainer", container);
if (replace) {
container.empty();
error.removeClass("input-validation-error-+-").appendTo(container);
}
else {
error.hide();
}
//For Validation Toggel Start
debugger;
if ($(inputElement).parent().hasClass("selectize-input")) {
$(inputElement).parent().parent().parent().addClass("md-input-danger");
var container = error.data("unobtrusiveContainer");
container.removeClass("field-validation-valid").addClass("field-validation-error");
}
}
I did lots of research for this but i didn't get any proper solution.
please help me to solve this issue.
Thanks
add below JQuery code in document ready to validate your selectize dropdown
$.validator.setDefaults({
ignore: ':hidden:not([class~=selectized]),:hidden > .selectized, .selectize-control .selectize-input input'
});

Retrive javascript properties from html page using C#

I want to know if there is a way to get specific property of javascript function from a webpage using c#,
here is the function I found within the site :
(function($){
window.Ibles.pageContext = $.extend(window.Ibles.pageContext, {
numStepsByWordCount: 1,
allSteps: true,
ibleID: "EPAOKDUH8I455QP",
ibleUrl: "/id/PVC-longbow/",
ibleType: "Step by Step",
ibleCategory: "outside",
ibleChannel: "survival"
});
})(jQuery);
I need to get the ibleID property.
Thx before
You can extract the value easily by using a regular expression:
var match = Regex.Match(content, "ibleID: \"(?<id>\\w+)\"");
if (match.Success)
{
var id = match.Groups["id"].Value;
}
else
{
// id not found
}

Regular Expression to avoid HTML tags and empty values

I have applied a textbox click validation and wanted to avoid any html tags in text box also the simple < (open tag) and >(close tag). The below code is working for but i want to add additional validations also for empty strings and other tags in html. Can some one please help modify the regex for the requirement.
function htmlValidation()
{
var re = /(<([^>]+)>)/gi;
if (document.getElementById(’<%=TextBox2.ClientID%>’).value.match(re)){ document.getElementById(’<%=TextBox2.ClientID%>’).value = “”;
return false;
}
return true;
}
Corrected Code above
In my opinion, I believe you'll have a good hard work if you want to validate such things.
Instead of preventing HTML content in a text box, other solution could be just html entity encode Text property, so <p>a</p> would be converted to >p<a>p<.
Result of that is you're going to render the HTML "as text" instead of getting it interpreted by Web browser.
Check this MSDN article:
http://msdn.microsoft.com/en-us/library/73z22y6h(v=vs.110).aspx
$("#<%= btnAdd.ClientID %>").click(function () {
var txt = $("#<%= txtBox1.ClientID %>");
var svc = $(txt).val(); //Its Let you know the textbox's value
var re = /(<([^>]+)>)/gi;
if(txt.val()!=""){
if (!txt.val().match(re)) {
//my Operations
//goes here
});
return false;
}
else {
alert("Invalid Content");
}
}
else {
alert("Blank value selected");
}
I have used Jquery function to check for regular expresion. This question is a linked question with
Using Jquery to add items in Listbox from Textbox
Now i can mark this as my final answer.

Open a new window/tab

I am working on a donations website. In my page, I have a textbox which accepts a numeric value from the user (that is, money to be donated).
In my code-behind, I have a method which checks whether the value in the textbox is numeric. The method generates an error message if the number is invalid.
I also have a JavaScript which, after checking that the value in the textbox is numeric, opens a new tab to the website confirmation page, thanking the user for his donation. Here is the code of the javascript:
<script type="text/javascript">
function Open_Window()
{
var textbox = document.getElementById('DonationTextBox');
if (textbox.value != "")
{
if (isNan(textbox) == false)
{
window.open("DonationConfirmation.aspx")
}
}
}
</script>
The problem is that the tab is NEVER opened, even if the number is valid. Can you please help me solve this problem? Thank you.
P.S.
Here is the code of the button that initiates the validation:
<asp:ImageButton ID="PayPalButton2" runat="server" ImageAlign="Middle"
ImageUrl="Resources/Icons/PayPalCheckOut.gif"
onclick="PayPalButton2_Click" OnClientClick="Open_Window()"/>
The function name is isNaN. Note: The final 'N' is capital. That should solve your problem.
<script type="text/javascript">
function Open_Window()
{
var textbox = document.getElementById('<%=DonationTextBox.ClientID%>');
if (textbox.value != "" && !isNaN(textbox.value)) {
window.open("DonationConfirmation.aspx");
}
}
</script>
edit
instead of isNan should be isNaN (javascript is casesensitive)
Shouldn't this line...
if (isNan(textbox) == false)
be this instead...
if (isNan(textbox.value) == false)
First, I would recommend explicitly parsing the number, not relying on the implicit ToNumber operation that will be applied when you pass a string into isNaN. Presumably your users are inputting decimal, so if it's meant to be a whole number (e.g., 10), use:
var num = parseInt(textbox.value, 10);
If it's meant to be a number with a fractional component (e.g., 10.5), use:
var num = parseFloat(textbox.value);
You probably want parseFloat for a currency value.
Then your if condition becomes isNaN (note that the final N is capped) on num:
<script type="text/javascript">
function Open_Window()
{
var textbox = document.getElementById('DonationTextBox');
var num = parseInt(textbox.value, 10);
if (!isNaN(num))
{
window.open("DonationConfirmation.aspx")
}
}
</script>
And lastly, are you sure that the client-side ID of the textbox really is 'DonationTextBox'? ASP auto-generates client-side IDs, you may need to use ClientID instead, e.g.:
var textbox = document.getElementById('<%=DonationTextBox.ClientID%>');
Here is a stripped down working jsFiddle example:
http://jsfiddle.net/pjgalbraith/QZeSF/
The html:
Open
<textarea id="donationTextBox">1</textarea>​
And the js:
function openWindow() {
if($('#donationTextBox').val() && isNaN($('#donationTextBox').val()) === false)
window.open("http://www.google.com/", "mywindow");
}
$(document).ready(function() {
$('#PayPalButton2').click(function(){
openWindow();
});
});
​

control names in a custom validator .NET Client Side Validation

I have a gridview with three columns of textboxes. It can have as many rows as necessary but its usually only about 5 rows. Each row needs to be validated.
I want to create a client side validator that sums 2 of the columns together and compares it with the third column to check that the user has entered the data correctly.
Just in case you are wondering, it's part of the spec that the operator must enter the third column rather than simply summing the two previous columns together in the code behind. This is done to ensure the operator is transcribing the information correctly.
I am trying to use the custom validator in .net to create this client side validation. but I can't find a way to pass to it the names of the three text boxes.
I can give it the target controls name using the ControlToValidate parameter, but how do I pass in the other two control id's ?
I am looking for the 'proper' way to do this, one thought is to create an array in javascript referenced by the controltovalidate's name.
DC
I solved the problem. not an elegant solution but it works.
first I placed the code into a div on the page
<div align="right"><asp:CustomValidator ID="RowValidator" runat="server"
ErrorMessage="Total of #total# does not equal 1st Preference + Ticket"
ControlToValidate="Total" ValidateEmptyText="True"
ClientValidationFunction="CheckRow" SetFocusOnError="True" EnableClientScript="True"
enableViewState="False" Display="Dynamic"></asp:CustomValidator></div>
Then I created a JavaScript function...
function CheckRow(sender,args) {
// get the name of the control to validate
try {
args.IsValid = true;
ctv = sender.controltovalidate;
// get the data from the other controls
nt = document.getElementById(ctv.replace('_Total','_NonTicket'));
t = document.getElementById(ctv.replace('_Total','_Ticket'));
if (nt && t) {
v1 = Number(nt.value);
v2 = Number(t.value);
v3 = Number(args.Value);
if ((v1 + v2) != v3){
msg = GetMessage(sender);
sender.innerHTML = msg.replace("#total#",Number(args.Value));
args.IsValid = false;
return false;
}
}
}
catch (e) {
// something wrong default to server side validation
}
return true;
}
This is called by the custom validator for each row I use the controltovalidate parameter of the sender to get the name
then its a matter of a bit of string manipulation to get the names of the other fields.
Once retrieved you can do what you like, in my case I add and compare. if there is an error the Isvalid flag is cleared and the message is modified to suit.
The getmessage function is required because I alter the message to give a more meaningful error message
/*
get the error message from the validator
store it so it can be retrieved again
this is done because the message is altered
*/
function GetMessage(sender){
msg = window[sender.id+"_msg"];
if (!msg){
msg = sender.innerHTML;
window[sender.id+"_msg"] = msg;
}
return msg;
}
The getmessage function keeps a copy of the original message so if the user makes a mistake more than once the message can be retrieved in its pristine form, other wise the first time we edit a message we overwrite the placeholder (#total#).
DC

Categories

Resources