I have a textbox, and it needs not allow the user to enter any special characters. He can enter:
A-Z
a-z
0-9
Space.
One more condition is the first letter should be alphabetic.
How can I do a JavaScript verification on each keypress?
add a onKeyUp="javascript:checkChar(this);" to the input box.
function checkChar(tBox) {
var curVal = tBox.value;
if ( /[^A-Za-z0-9 ]/.test(curVal) ) {
//do something because he fails input test.
}
}
alernatively to check JUST the key that was pressed you can grab the keycode from the event like so:
onKeyUp="javascript:checkChar(event);"
function checkChar(e) {
var key;
if (e.keyCode) key = e.keyCode;
else if (e.which) key = e.which;
if (/[^A-Za-z0-9 ]/.test(String.fromCharCode(key))) {
//fails test
}
}
missed the part about first char, but you can do a test on the textbox value as in the first example:
/^[A-Za-z]/.test(curVal)
or even use the second method but pass the text box as well so you can get it's full value.
This function will check the string given to it for those criteria:
function checkvalue(value) {
return value.match( /[A-Za-z][A-Za-z0-9 ]*/ );
}
You can then use that in an onkeypress event, passing in the current value.
Now that we have HTML5, you don't even need to use JavaScript. You can use the pattern attribute.
<input type="text" pattern="[A-Za-z][A-Za-z0-9 ]*" title="Description of format" />
The pattern attribute should contain a regular expression defining the format. And title should contain a human-readable description of the format.
Then on validation, depending on the browser, the browser will outline the field in red and/or display a message stating your description of the format.
This tutorial goes into more detail: HTML5 Input Validation Tutorial.
You should check pressed key in onkeydown event handler of the textbox and if it doesn't conform conditions then return false from the handler. Using keyup will not allow you to prevent char from being actually inputted in the textbox.
I don't think you should check on each keypress, it could be very annoying for the user.
Just check the input when it loses the focus, or when submiting.
To do it, you can use a regex and use this pattern:
`/[a-z]{1}[a-z0-9]/i`
You can also take a look at the JQuery Validation Plugin
Related
I work in Animate CC and I only need 2 things. Limit the amount of caracters in a input text component (maxlength = 15). Then, add a second input text component and force the user to only enter numbers (maxlength = 2).
The pictures shows my windows and the option I got. How can I achieve this? I've learned HTML5 in Animate by myself coming from working in AS2 before. So I would need the answer to be detailed for a beginner like me.
Thank you very much.
In terms of limiting the amount of characters in the input field you could add something like this to the html output that Animate CC produces when you publish:
document.getElementById("test").maxLength = "15";
Where your input field is given the name test in the properties panel.
To answer your other question, I don't think you can control what the user can type into an input field, only validate that input afterwards. I think you would need to use JavaScript (maybe trapping a keyup event) to work this.
Actually yes you can specify what characters the user can use.
In the example below the component's name is input1 and we allow only digits
********************* ALLOW ONLY NUMBERS IN INPUT ******************
if (!this.myInput_change_cbk) {
function myInput_change(evt) {
// change value here
console.log(evt.target.value);
var regex = /[^0-9]/g;
evt.target.value = evt.target.value.replace(regex, "");
// End your custom code
evt.target.maxlength = 2;
}
$("#dom_overlay_container").on("keyup", "#input1", myInput_change.bind(this));
this.myInput_change_cbk = true;
}
I have a ASP.Net gridview and in itemTemplete I have textbox for input purpose. The problem is some textbox is for numeric input and other for Character and some accept Mobile no and 1 row is for IP address.
Now i want to validate rows as per Row in gridview?
is it possible if possible then how ?
here im giving an example.Not an exact answer.So try to understand the logic.Here im giving how to validate phno and only alphabets in name.remaining you can get, like the same way.
Because of dynamic generation of textboxes we cant create validations on it.So i use "javascript"
First you need to click "View Page source"(Right click on browser page).In that we can see the "Id"s of dynamically generated textboxes.here i take two textboxes for phno and name in gridview.i get their ids by seeing their html.(Right click on browser->view page source).i get their ids like "GridView1_TextBox1_0" for name"GridView1_TextBox1_1" for phone.By using ids i create validation using Javascript.Write the below code in Head Section of Page.
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<script type="text/javascript">
function validate() {
var phno = document.getElementById("GridView1_TextBox1_1").value;
var namechar = document.getElementById("GridView1_TextBox1_0").value;
var phoneno = /^\d{10}$/;
var name = /^[a-zA-Z]+$/;
if (!namechar.match(name)) {
alert("please enter alphabets only");
return false;
}
if(!phno.match(phoneno))
{
alert("please enter valid phno");
return false;
}
}
</script>
In this way i validate textboxes which are generated dynamically.once again its not exact answer.its a logic by using javascript.
Limitation:
Hence Javascript is client side technology.if user disable the javascript.it not works.
I have applied validation through JQuery Validation Plugin on my page. The validation works fine but once the Clear button is hit to clear out all the fields on the form, and then the save button is clicked again, the validation doesn't fire and the form gets submitted. I have called the following javascript function on click of Clear button to clear out all the form fields :-
function ResetForm() {
jQuery(':input', '#form1')
.not(':button, :submit, :reset, :hidden')
.val('')
.removeAttr('checked')
.removeAttr('selected');
return false;
}
The Clear button is on a ChildPage and ResetForm function is on the MasterPage. Anybody have any guess why its getting submitted after clearing the fields ?
input is an element and not a attribute or a pseudo selectable, the main issue I see in your code is the : within the :input
Try changing to jQuery('#form1 input') to fetch the list of inputs
Also change the not() command to select filter the inputs by type
.not('[type="button"], [type="submit"], [type="reset"], [type="hidden"]')
also as for :hidden there's several factors you should know about this.
They have a CSS display value of none.
They are form elements with type="hidden".
Their width and height are explicitly set to 0.
An ancestor element is hidden, so the element is not shown on the page.
In light of your comment please try this tested version:
function resetForm()
{
$("#form1").find(':input').each(function()
{
var jelem = $(this);
switch(this.type)
{
case 'password':
case 'select-multiple':
case 'select-one':
case 'text':
case 'textarea':
jelem.val('');
break;
case 'checkbox':
case 'radio':
jelem.attr('checked',false);
}
});
}
#source: http://www.electrictoolbox.com/jquery-clear-form/
Another way to do this is to create a hidden input in your form but set the type as reset like so:
<input type="reset" style="display:none" />
and then do:
function resetForm()
{
$("#form1[type='reset']").click();
}
Actually the error was something else, the code provided by RobertPitt is correct for clearing of form fields and my code was also correct for clearing of form fields. But the problem is that, on the clear button I had applied a class="cancel" so that the form should not get submitted because it was an aspx:button.
But according to what is written in JQuery docs, clicking of a button whose class is cancel should skip the validation, but after that if I click on a normal submit button validation should fire which was not firing in my case.
I just removed the cancel class and it worked.
Does this help?
Reseting the form when usering the jquery validations plugin
I have sort of a table with a radio-button column. I managed to make radio-button column work dynamically inserting into a cell (div if matter). But, on postback innerHtml hasn't been updated with "checked" attribute.
Could you give me an idea how can I find out (on the server) if radio-button has been checked?
More info: This is on user control inside update panel.
This would be good post on my topic, still doesn't help
Any reason you cannot use a standard asp:RadioButton and use javascript to ensure it is mutually exclusive. I have done this before by adding a custom attribute to the radiobutton and then using a js function to uncheck all items with that attribute and then check the selected one. This works around the IE issue which prevents the groupname attribute from working on radioboxes that are in different containers.
radioButton.InputAttributes.Add("ClientGroupName", "grpRadioList");
radioButton.InputAttributes.Add("onclick",
string.Format(
"javascript:radiobuttonToggle('{0}','ClientGroupName','grpRadioList');"
,radioButton.ClientID));
and use the following JS to uncheck all radios and then check the one you want.
Note i used InputAttributes instead of Attributes as the radiobutton is wrapped inside a span tag so InputAttributes is for items added to the actual input control rather than the span.
function radiobuttonToggle(selectedRB, attribName, attribValue)
{
var objRadio = document.getElementById(selectedRB);
for(i = 0; i < document.forms[0].elements.length; i++)
{
elm = document.forms[0].elements[i];
if (elm.type == 'radio')
{
if(elm.getAttribute(attribName) == attribValue)
elm.checked = false;
}
}
objRadio.checked = true;
}
You can then expose radioButton.Checked as a property in your CS file and reuse this as a control.
Check Form.Request("radio-name") != null
You only get a non-null value when it's been checked.
Make sure your page elements are being rebuilt correctly on postback. Any binding process that inserted the radio buttons the first time around will have to be re-run before you can access them the second time.
Here is a working example, first I add radios to my webform by the method you linked :
function addRadio()
{
try{
rdo = document.createElement('<input type="radio" name="fldID" />');
}catch(err){
rdo = document.createElement('input');
}
rdo.setAttribute('type','radio');
rdo.setAttribute('name','fldID');
document.getElementById('container').appendChild(rdo);
}
Then at code behind I used only the code below to get the radio's value :
string value = Request["fldID"];
So, be sure you're trying to get the name of the radio buttons at server side. You should use name attribute at server side, not id.
Suppose I have a table like:
create table
{
id numeric(5,3),
code varchar(10)
}
I have two text boxes in my form for the two fields.
Suppose if I type 1234578 in the first text box the error has been thrown in ASP.NET because I crossed the limit.
How can I validate in JavaScript or some other way for that particular range validation?
Let's take one textbox only. Attach an 'onchange' event handler to your textbox like this:
<input type="text" onchange="handleChange(this);" />
Then declare a script for validation like this:
<script>
function handleChange(input) {
if (input.value > ..your_value_here..) alert ("Invalid input");
}
</script>
Please note that the alert pop-up used here should not be actually used. Use a more subtle reminder at a more appropriate moment. The alert here is only to make things simple.