i need to control the numbers of characters in an input field using jquery ...
ive got some control already but, i dont know what else to do ....
var foo = function(){
if($('#foo1').val() == ''){
$('.foo_foo_c').load('../html/message_error_number.html');
}else{
$('.foo_foo_c').load('../html/foo_foo.html',function(){
listaStyle();
listaPagadasStyle();
listaDetalleLlamadasStyle();
});
}
};
Look at using the jQuery validation plugin and set up maxLength or rangeLength rule in addition to requiring that it be a number.
I think you want something like the Alphanumeric plugin.
Related
<input id="phone" name="phone" placeholder="(XXX)XXX-XXXX" type="tel"
pattern="^(?:\(\d{3}\)|\d{3})[- ]?\d{3}[- ]?\d{4}$" required="true"/>
How can I validate if that pattern is used in JavaScript for browsers that don't support the pattern attribute?
Thank you for your input -- I've tried doing several options below, but I can't seem to get anything to trace out as "true" -- the RegExp works in the HTML pattern field for FireFox and Chrome. But it's always returning false when I'm trying to utilize it with javaScript?
http://pastebin.com/M0Pdn2Z3
There are a number of polyfills that will enable this in older browsers:
nwxforms, no dependencies
HTML5 Form Shim, requires jQuery
h5Validate, also requires jQuery
I'd recommend polyfilling -- this doesn't change the behavior for modern browsers but emulates it in old ones. (An aside: the Modernizr polyfills list is fantastic.)
You could also write it yourself; some other answers show how that's done.
Create an onchange event that reads the pattern attribute and runs it against the value.
// Only bind event if we need to
if(!('pattern' in document.createElement('input'))){
// Bind the event
document.getElementById('phone').addEventListener('change', function(){
// Get the regex and value then test it
var regex = new RegExp(this.pattern),
val = this.value,
valid = regex.test(val);
// Is it valid?
if(!valid){
// Do something when it's not
}
});
}
You should validate when submitting the form, or losing focus from the input.
If you use jQuery, this will work for all elements with pattern attribute:
$('[pattern]').each(function() {
if (!$(this).val().match($(this).attr('pattern')))
alert('Bad value');
});
If not, you can do something for this (similar):
var inputs = getElementsByName('input');
for (var index in inputs) {
var input = inputs[index];
var pattern = input.getAttribute('pattern');
if (pattern != '' && pattern != null) {
if (!input.value.match(pattern))
alert('Bad value');
}
}
These will loop through the attributes that have a pattern to identify against, check them, and alert the user if there's a problem.
Of course, you can change the alert to whatever way you would like to handle it (for example, return false to cancel the form submission).
I haven't tested this code, but that's the gist of it.
You can use polyfill or add onchange event to your input.
document.getElementById('phone').addEventListener('change', function(){\
// returns true if input matches regexp, otherwise it returns false
var isValid = RegExp(this.pattern).test(this.value);
});
var regex = /^(?:\(\d{3}\)|\d{3})[- ]?\d{3}[- ]?\d{4}$/;
if(phone.value.match(regex)){
console.log('true');
}else{
console.log('false');
}
I just ended up using this... It worked. #_#
I need to trim all the trailing white spaces from the text elements of the form. I need to do it in minimal number of steps. As soon as i press onsubmit, it should trim all the white spaces and then perform the further operations. Is there any script available? If not then can you please help me to achieve my Goal. Currently i need to manual identify each element and then perform a trim like.
var username = myform.elements['username'].value;
username.trim();
How to generalize it?
$('input').val(function(_, value) {
return $.trim(value);
});
$("form").children().each(function(){
this.value=$(this).val().trim();
})
will trim all textbox and textarea inside form tag but don't write unnecessary code inside form.
Use
var allInputs = $(":input");
to get all form elements. Iterated using each function and trim it.
It will be something like this (not tested)
var allInputs = $(":input");
allInputs.each(function() {
$(this).val($.trim($(this).val()));
});
$('#yourformid').submit(function(){
$(':input').each(function(){
$(this).val($.trim($(this).val()))
})
return true;
});
$('#formid').find('input:text').each(function(){
$(this).val($.trim($(this).val()));
});
So I'm using the minimal regex [0-9]* for the iPhone number pad in my HTML5 pattern attributes. I also had a submit function that sends an email through the server. Everything was working good until I realized it was trying to send the form re3gardless of whether the browser was trying to block submit based on incorrect user input.
So I did the following but can't get it to work:
<script>
function validate(){
var phone=/[0-9]*/;
var x=document.forms["form"]["contactnum"].value;
if (x!=phone){
alert("Contact Number must be a valid phone number (no dashes)");
return false;
}
else {
alert("Thank you! We have received your information and will contact you shortly.");
ajax('{{=URL('new_post')}}',['phone'], 'target');
return false;
}
}
</script>
The problem is I can only get it to work if I set if (x==null || x=="") in the if statement. If I try to match it with any other var it will always say I'm not matching the [0-9]*. I already have written several complex regex's but really don't want to use anything on this simple form. I just wanted the number pad on the iPhone and not to submit if it wasn't a digit or null. I don't even care if they put in a "2" for the phone, just so long as it's a digit.
Thanks.
if ( x.match(/^[0-9]+$/) ) {
// valid
} else {
// invalid
}
That's not how you use a regular expression:
if (!phone.test(x)) ...
Also if you want to match a string with nothing but digits, try
var phone = /^\d*$/;
That will match the empty string too; use + instead of * if you want at least one digit.
You actually seem to have two questions in one here. For the first part, you haven't shown how you're using validate(), but remember that the onsubmit handler, itself, must return false to keep the browser from completing the normal submit process. For example, the following will not work:
$('#myform').submit(function(){
validate();
});
But this would successfully stop the default submit process:
$('#myform').submit(function(){
return validate();
});
validate() would return false, and then your handler returns the same.
I have asp:textbox I want to restrict the text box to allow only integer values.
How can I do that using javascript in asp.net.
If you use the replace function and some regualar expressions you will be able to do this.
<input type="text" name="textbox" onkeyup="integersOnly(this)">
<script type="text/javascript">
function integersOnly(obj) {
obj.value = obj.value.replace(/[^0-9-.]/g,'');
}
</script>
That will also keep in the decimal place.
If you just want integers use:
obj.value = obj.value.replace(/[^0-9]/g,'');
All this function is doing is taking what is input and removing any characters that are not numbers.
Alternatively you can do this in jQuery. If you use jQuery let me know and I will let you know how I do it.
EDIT
Following on from your comment you could use the following updated function:
var integer_only_warned = false;
function integersOnly(obj) {
var value_entered = obj.value;
if (!integer_only_warned) {
if (value_entered.indexOf(".") > -1) {
alert('Please enter an integer only. No decimal places.');
integer_only_warned = true;
obj.value = value_entered.replace(/[^0-9]/g,'');
}
}
obj.value = value_entered.replace(/[^0-9]/g,'');
}
What this is doing is first checking if a decimal has been entered. If it has then it is warning the user and then removing the decimal place. I have also added a check, so that the warning only comes up once every page load.
Hope that helps.
Use a RegularExpressionValidator control and set the EnableClientScript property to True.
Check this example.
Restrict Characters and Allow only Integers in Textbox using JavaScript
Just to throw this in too, if you happen to be using AJAX Control Toolkit, there is an extender already built that makes filtering content a snap: http://www.asp.net/ajaxLibrary/AjaxControlToolkitSampleSite/FilteredTextBox/FilteredTextBox.aspx
On a form, I need to make sure that all fields are filled in and that the phone # and email address are valid. I tried using a jQuery validation plugin but it changed the page's look and feel. The plugin also was dynamically looking for some css files in some spot that was unexpected.
I love jQuery but the plugin seemed too much for what I wanted.
Since all I need to do is to make sure the fields are not empty and that the phone number is valid and email is valid, what javascript functions do you suggest? I will still use jQuery core.
Serverside we want to use apache commons PhoneNumberFormatter and same with email validation.
Thanks!
I think you're looking for JavaScript regular expressions, using the RegExp object that comes as a standard part of JavaScript. You can use that to perform basic checking of email addresses and phone numbers.
e.g.
function emailIsValid(emailAddress) {
var emailRegex = /\b[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}\b/;
return !!emailAddress.match(emailRegex);
}
The code above is not tested, but it should give you an idea of how to do it. Just do the same again for the telephone number, and then do something like this:
if (emailIsValid(emailAddressValue) && telephoneNumberIsValid(telephoneValue)) {
//Submit form
} else {
alert ("There are errors on the form, please correct and invalid data");
}
In this jsfiddle you'll find a JQueryless method I use to check form fields. It checks all form fields periodically using an interval function.
Everyone focused on the email and phone number validation, but encase you need help with detecting empty text boxes and even just how/when to call the code for email/phone validation:
<script type="text/javascript">
function validate()
{
var curVal;
for(var index = 1 ; index < 15 ; index++)
{
curVal = document.getElementById("textbox_"+index).value
if(curVal == "")
{
alert("empty text box")
return(false); //false will stop the form from submitting
}
if(index = 5)// email text box
{
//validate email
}
}
}
</script>
<type="input" id="textbox_1">
<type="submit" value="Submit" onClick="validate()">
here is one for email
function checkemail()
{
var str=email
var filter=/^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z] {2})?)$/i
if (filter.test(str))
testresults=true
else
{
alert("Please input a valid email address!")
testresults=false
}