I wanted to allow only characters in a textbox and space in between two characters.I am trying to avoid any unwanted characters and blank string in following Javascript code.
var filter = "^[a-zA-Z''-'\s]{1,40}$";
var label = $('#<%= txtName.ClientID %>').val();
if ((label.length > 0) && (label!= '')) {
if (label.match(/^[a-zA-Z \s]{1,40}$/)) {
if (label.match(/^\s$/)) {
alert("Please Enter a Valid name");
return false;
}
else {
$("#myModal").dialog('open');
}
}
else {
alert("Please Enter a Valid name");
}
}
else {
alert("Please Enter a Valid name");
}
This is working fine for everything except when user enters more than 1 space in the textbox. I was thinking that label.match(/^\s$/)) will take care of blank string or blank spaces.
Thanks
It looks like this is a job for 0 or more (the RegEx *)! (Pardon the exclamation, I'm feeling epic this morning)
/^\s$/ means "contains only one space"
I believe you are looking for
/^\s*$/ means "contains only zero or more spaces"
you should use + sign in regular expression for more than one entities.suppose if you want multiple spaces then use like var expr=/(\s)+/
Related
I've been doing a lot of searching, chopping and changing, but I'm...slightly lost, especially with regards to many of the regex examples I've been seeing.
This is what I want to do:
I have a text input field, size 32.
I want users to enter their telephone numbers in it, but I want them to enter a minimum of 10 numbers, separated by a single comma. Example:
E.g. 1
0123456789,0123456789 = right (first group is >=10 numbers, second group = >=10 numbers & groups are separated by a single comma, no spaces or other symbols)
E.g. 2
0123456789,,0123456789 = wrong (because there are 2 commas)
E.g. 3
0123456789,0123456789,0123456789 = right (same concept as E.g. 1, but with 3 groups)
I've got the following, but it does not limit the comma to 1 per 10 numbers, and it does not impose a minimum character count on the number group.
$(document).ready(function(){
$("#lastname").keypress(function (e) {
//if the letter is not digit then display error and don't type anything
if (e.which != 8 && e.which != 0 && String.fromCharCode(e.which) != ','
&& (e.which < 48 || e.which > 57)) {
//display error message
$("#errmsg").html("Digits Only").show().fadeOut("slow");
return false;
}
});
});
Preferably, I'd like to warn the user of where they are going wrong as well. For example, if they try to enter two commas, I'd like to specifically point that out in the error, or if they havent inserted enough numbers, i'd like to specifically point that out in the error. I'd also like to point out in the error when neither a number or a comma is inserted. I'd like to ensure that the tab, and F5 keys are not disabled on the keyboard as well. And very importantly, I'd like to specifically detect when the plus or addition key is used, and give a different error there. I think I'm asking for something a little complex and uninviting so sorry :/
The example code I provided above works pretty well across all browsers, but it doesn't have any of the minimum or maximum limits on anything I've alluded to above.
Any help would be appreciated.
As far as a regex that will check that the input is valid (1-3 phone numbers of exactly 10 digits, separated by single commas), you can do this:
^\d{10}(,\d{10}){0,2}$
Try like the below snippet without Regex
var errrorMessage = '';
function validateLength (no) {
if(!no.length == 10) {
return false;
}
return true;
}
function validatePhoneNumbers (currentString, splitBy) {
if(currentString) {
var isValid = true,
currentList = currentString.split(splitBy);
// If there is only one email / some other separated strings, Trim and Return.
if(currentList.length == 1) {
errrorMessage = 'Invalid Length in Item: 1';
if(validateLength( currentString.trim() )) isValid = false;
}
else if(currentList.length > 1) {
// Iterating mainly to trim and validate.
for (var i = 0; i < currentList.length; i++) {
var listItem = currentList[i].trim();
if( validateLength(listItem ) ) {
isValid = false;
errrorMessage = 'Invalid Length in Item:' + i
break;
}
// else if for some other validation.
}
}
}
return isValid;
}
validatePhoneNumbers( $("#lastname").val() );
I want to compare a value of a field centerCode which is entered by a user into an input field. Then I want to check if it is a number and show the appropriate alert accordingly. I am not able to compare the value or variable number with the variable code .
var numbers =/^[0-9]+$/;
var code = $scope.Nuser.centerCode;
alert(code);
if(code.val(numbers))
{
alert(code.val(numbers));
}
else
{
alert("enter numbers only");
}
You're along the right lines. Numbers needs to be a Regex though, and you need to use the test function to check the input against it. The test function will return true if the string is all numbers, or false if there is anything else in it.
var numbers = new RegExp(/^[0-9]+$/);
var code = $scope.Nuser.centerCode;
if(numbers.test(code))
{
alert('code is numbers');
}
else
{
alert("enter numbers only");
}
I would suggest you to use ng-pattern instead . Something like following :
<input type="text" ng-pattern="/^[0-9]{1,7}$/" ng-model="inputNumber"/>
It will only allow the user to enter the number.
You can use angular.isNumber to check if the entered value is a number or not. Try something like the following :
if(angular.isNumber($scope.Nuser.centerCode)){
alert('Center Code is a number');
}else {
alert('Center Code is not a number');
}
Hope this will do the trick.
You can simply convert string to number and test is it's NaN (Not a Number)
isNaN(+$scope.Nuser.centerCode)
if it's false it means your centerCode contain only numbers
try this hope this is what you are looking for
if(angular.isNumber(value))
{
//your code here
}
I am using following script to validate password. Aims For validations are :
Password field should not be empty
Password Length should be between 6 and 10 characters
Password should not contain spaces and special characters
Password should be Alphanumeric.
But With following code , it passes first 3 aims but even after entering Alphanumeric text, it is till alerting:
"Password Should Contain Alphabet And Numbers Both".
Need your help
Code is :
if(document.subForm.password.value==""){
alert("Please Enter Your Desired Password....");
document.subForm.password.focus();
return false;
}
if(document.subForm.password.value.length < 6 || document.subForm.password.value.length > 10){
alert("Password Length Should Be In Between 6 And 10 Characters.");
document.subForm.password.focus();
return false;
}
var re = /^[\w\A-Z]+$/;
if(!re.test(document.subForm.password.value)) {
alert ("Your Password Has Spaces In Between The Words \n\nOr\n\nIt Contains Special Characters.\n\nThese Are Not Allowed.\n\nPlease Remove Them And Try Again.");
document.subForm.password.focus();
return false;
}
var realphanumeric = /^[a-z_A-Z_0-9]+$/;
if (!realphanumeric.test(document.subForm.password.value)){
alert("Password Should Contain Alphabet And Numbers Both");
document.subForm.password.focus();
return false;
}
Aragon0 suggested to use an open-source script from dropbox to check password strength. I recommend checking it out.
If you'd like one regular expresion to check everything:
^\w{6,10}$
Explanation:
From start (^ ) to end ($) of the string...
match only alphanumeric characters ([A-Za-z_0-9]),
with a length of 6-10 characters ({6-10})
If you want to force the user to have at least one number you can do that like this:
^(?![A-Za-z_]+$)\w{6,10}$
Your regex
/^[a-z_A-Z_0-9]+$/
doesn't do what you want. It will match the password "Test" but not "te#st".
You could use two regexes, which both need to match:
/[a-zA-Z]+/
/[0-9]+/
Btw, you should not enforce alphanumeric passwords or length constraints. You could use Dropbox's password strength script (https://github.com/dropbox/zxcvbn)
Some sample code with zxcvbn:
<script src="//cdn.jsdelivr.net/zxcvbn/1.0/zxcvbn-async.js" />
<script>
var result = zxcvbn(document.subForm.password.value);
if(result.entropy<56) // 56 is very secure, you could also lower it to 48 if you need to.
{
alert("Your password is too weak. It would be cracked " + result.crack_time_display);
return false;
}
</script>
I have created an external JavaScript to validate a form I created in HTML. Some of the validation works, but when I use the same code to validate other fields it will not work. E.g. postcode must contain numbers - if not, postcode is invalid.
I tried using the same code for a credit card, i.e. credit card must have 16 digits - if not, the credit card number is invalid. I wrote the code for postcode and it worked, but when I tried to reaarrange it to suit the credit card function, it did not work. Not too sure why? Should I have used a different function?
Here is my external javascript:
function validateForm()
{
if (isNaN(document.getElementById("postcode").value))
{
alert ("Your postcode is not valid");
}
else
{
alert ("You have entered your postcode correctly");
}
if (document.getElementById ("email").value.length < 5 ||
document.getElementById ("email").value.indexOf("#")== -1)
{
alert("Please enter your email min 5 chars and include # symbol");
document.getElementById("email").focus();
return false;
}
if (isNaN(document.getElementById("creditcard").value))
{
alert ("Your creditcard is not valid");
}
else
{
alert ("You have entered your creditcard correctly");
}
alert("Thank you for your submission!");
return true;
}
So first off, you probably don't want to prompt the user with 10 error dialogs at a time.
So you should nest your if else clauses & the function will stop after the first error.
Second, isNaN is doubtfully a good evaluator because input.value may return a value of type string. Using a regex is a more robust way of error checking inputs. Third, you want to account for the user's confusion mistakes. Users often think (me too): 'wait, should I also write the dash on my credit card here?'.
So you'll remove dots, dashes & whitespace before proceeding (those could unknowingly be included). Other chars are just invalid. For your credit card input, that would be:
var ccVal = document.getElementById("creditcard").value;
// remove dots, dashes & whitespace
ccVal = ccVal.replace(/(\s|\.|\-)/g, '');
// if any other chars there, input value = incorrect & stop function
if ( ccVal.match(/\D/) ) {
alert('A credit card number only has decimals, silly.');
return false;
} else {
// Check for length now
if ( ccVal.length !== 16) {
alert('A credit card has 16 decimals, silly.');
return false;
} else {
// more checks
document.getElementById('myform').submit()
}
}
See an implementation example here: http://jsbin.com/betawahi/1/edit
isNaN checks if the value is not an integer, you'll need an additional check for the length.
Keeping the code similar to the way you've set out the rest of the function, to check if the credit card is a number and a length of 16, you'll want:
if( !(isNaN(document.getElementById("creditcard").value) && document.getElementById("creditcard").value.length === 16) {
alert("Credit Card Is Valid");
}else{
alert("Your Credit Card is Not Valid");
return false;
}
I would like to check if users enter correct phone number in, with help of jQuery, so far I got to this stage:
var phone = $("input#phone").val();
if (phone !== "") {
//Check if phone is numeric
$("label#phone_error").show(); //Show error
$("input#phone").focus(); //Focus on field
return false;
}
Basically it checks if phone number was entered and if it was, I would like to check if it is a numeric value and if it is not display the error messages.
Could anyone help with checking if it is numeric?
Try this ... it will make sure that the string "phone" only contains digits and will at least contain one digit
if(phone.match(/^\d+$/)) {
// your code here
}
There is a built-in function in jQuery to check this (isNumeric), so try the following:
var phone = $("input#phone").val();
if (phone !== "" && !$.isNumeric(phone)) {
//Check if phone is numeric
$("label#phone_error").show(); //Show error
$("input#phone").focus(); //Focus on field
return false;
}
You can use jQuery method to check whether a value is numeric or other type.
$.isNumeric()
Example
$.isNumeric("46")
true
$.isNumeric(46)
true
$.isNumeric("dfd")
false
I used this to check if all the text boxes had numeric values:
if(!$.isNumeric($('input:text').val())) {
alert("All the text boxes must have numeric values!");
return false;
}
or for one:
$.isNumeric($("txtBox").val());
Available with jQuery 1.7.
http://docs.jquery.com/Plugins/Validation/CustomMethods/phoneUS
Check that out. It should be just what you're looking for. A US phone validation plugin for jQuery.
If you want to do it on your own, you're going to be in for a good amount of work. Check out the isNaN() function. It tells you if it is not a number. You're also going to want to brush up on your regular expressions for validation. If you're using RegEx, you can go without isNaN(), as you'll be testing for that anyway.
I used this:
jQuery.validator.addMethod("phoneUS", function(phone_number, element) {
phone_number = phone_number.replace(/\s+/g, "");
return this.optional(element) || phone_number.length > 9 &&
phone_number.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/);
}, "Please specify a valid phone number");
if (!(/^[-+]?\d*\.?\d*$/.test(document.getElementById('txtRemittanceNumber').value))){
alert('Please enter only numbers into amount textbox.')
}
else
{
alert('Right Number');
}
I hope this code may help you.
in this code if condition will return true if there is any legal decimal number of any number of decimal places. and alert will come up with the message "Right Number" other wise it will show a alert popup with message "Please enter only numbers into amount textbox.".
Thanks... :)
for future visitors, you can add this functon that allow user to enter only numbers: you will only have to add jquery and the class name to the input check that into http://jsfiddle.net/celia/dvnL9has/2/
$('.phone_number').keypress(function(event){
var numero= String.fromCharCode(event.keyCode);
var myArray = ['0','1','2','3','4','5','6','7','8','9',0,1,2,3,4,5,6,7,8,9];
index = myArray.indexOf(numero);// 1
var longeur= $('.phone_number').val().length;
if(window.getSelection){
text = window.getSelection().toString();
} if(index>=0&text.length>0){
}else if(index>=0&longeur<10){
}else {return false;} });
I used this kind of validation .... checks the pasted text and if it contains alphabets, shows an error for user and then clear out the box after delay for the user to check the text and make appropriate changes.
$('#txtbox').on('paste', function (e) {
var $this = $(this);
setTimeout(function (e) {
if (($this.val()).match(/[^0-9]/g))
{
$("#errormsg").html("Only Numerical Characters allowed").show().delay(2500).fadeOut("slow");
setTimeout(function (e) {
$this.val(null);
},2500);
}
}, 5);
});
This isn't an exact answer to the question, but one other option for phone validation, is to ensure the number gets entered in the format you are expecting.
Here is a function I have worked on that when set to the onInput event, will strip any non-numerical inputs, and auto-insert dashes at the "right" spot, assuming xxx-xxx-xxxx is the desired output.
<input oninput="formatPhone()">
function formatPhone(e) {
var x = e.target.value.replace(/\D/g, '').match(/(\d{0,3})(\d{0,3})(\d{0,4})/);
e.target.value = !x[2] ? x[1] : x[1] + '-' + x[2] + (x[3] ? '-' + x[3] : '');
}