How to avoid to enter repeated number in input text form? - javascript

I'm trying past few days to solve input number form validation in javascript. The logic user doesn't allow to enter repeated same number like "00000000000", "11111111111". If they enter numbers on text field i have to show error message,
sample code,
var mobNumber = $('#phNo').val();
if(mobNumber.match("00000000") || mobNumber.match("1111111")) {
alert('Please enter valid phone number');
}

You could use following regex ^(\d)\1+$ :
^ asserts position at start of the string
(...) 1st capturing group
\d matches a digit (equal to [0-9])
\1 matches the same text as most recently matched by the 1st capturing group
+ Quantifier, matches between one and unlimited times, as many times as possible, giving back as needed
$ asserts position at the end of the string, or before the line terminator right at the end of the string (if any).
See following example:
function test(par){
if(par.match(/^(\d)\1+$/g)){
console.log(par + " is not valid");
}else{
console.log(par + " is valid");
}
}
test("11111111");
test("11131111");
test("111a1111");
test("010101010");
test("9999");
I hope it helps you. Bye

You can simply write code like
$(document).on('input', '#phNo', function() {
var mobNumber = $(this).val();
var res = mobNumber/(mobNumber/10);
if(res == 111111111) {
alert('Please enter valid phone number');
}
});
this is applicable for all numbers and you have to check the max and min length of the input ..

You can try like this,
var phone = "11111111";
var phonecount = phone.length;
var countLength = 0;
for (var i in phone)
{
if(phone.substring(0,1)==phone[i])
{
countLength = countLength + 1;
}
}
if (countLength == phonecount)
alert("Please enter valid phone number");

try this :
var checkPhone = function() {
phone_number = $('#phone').val();
res = (/^(.)\1+$/.test(phone_number) ? '1' : '0');
if(res == '1'){
return 'bad phone number';
} else {
return 'good phone number';
}
}
Test it here : JSFIDDLE

Related

Trying to get a prompt to limit the first three character of a prompt to letters only

So i have this code that i want to be able to limit what can be said in a prompt box using javascript. I am using a do and while statement to push out a prompt loop until the prompt meets the requirement, i am only allowed to use javascript. I want the first three characters of the prompt box to be only letters, however i think i have a problem with my regex! any help would be greatly appreciated.
function myFunction() {
var userInput = new Array();
var letters = /^[A-Za-z]+$/;
do {
userInput = prompt('Enter course code');
if (userInput.length != 7) {
alert("The input must contain 7 characters");
}
var userInput3 = userInput.substring(0, 3);
if (userInput3 != /[A-Za-z]+$/){
alert("The first 3 characters must be letters");
}
}
while (userInput.length != 7 && userInput3 != /[A-Za-z]+$/){
}
}
You just compare first 3 letter with string '/[A-Za-z]+$/'
Try this
function myFunction() {
var userInput = new Array();
var letters = /^[A-Za-z]+$/;
do {
userInput = prompt('Enter course code');
if (userInput.length != 7) {
alert("The input must contain 7 characters");
}
var userInput3 = userInput.substring(0, 3);
if (!/^[A-Za-z][A-Za-z][A-Za-z].*/.exec(userInput3)){
alert("The first 3 characters must be letters");
}
}
while (userInput.length != 7 && userInput3 != /[A-Za-z]+$/){
}
}
myFunction()
Using this regex ^[a-zA-Z]{3}.{4}$ you can achieve it in single if loop,
function myFunction() {
var userInput = new Array();
do {
userInput = prompt('Enter course code');
if (!/^[a-zA-Z]{3}.{4}$/.test(userInput)) {
alert("The input must contain 7 characters where first 3 characters must be letters");
}
}
while (!/^[a-zA-Z]{3}.{4}$/.test(userInput)){
}
}
myFunction();
I get the impression you're feeling your way through this at the moment, theres a lot you could do to make your code safer and more efficient in general. while loops are a dangerous way to kill time for a start.
In terms of your regexp problem, try using .test if you're looking for a boolean (true or false) response to your regexp test
For example
/([A-Z]|[a-z])/.test(userInput3)
will return true if all the characters are letters between a to z in lower or upper case ( | is or ).
if you add ! before the test you will reverse its boolean value (true becomes false and vice verse)
so you could go:
if (!/([A-Z]|[a-z])/.test(userInput3)){
/* do something if userInput3 contains anything other than the letters a-z in
upper or lower case */
}
so
You can try the below code.
function myFunction() {
var userInput;
//var regEx = new RegExp("^[a-zA-Z]{3}.{4}$"); // It Will check for first 3 must be characters and length 7
var regEx = new RegExp("^[a-zA-Z]{3}"); // It Will check for first 3 must be characters and not check for length
do {
userInput = prompt('Enter course code');
if (userInput.length != 7) {
alert("The input must contain 7 characters");
}
if (!regEx.test(userInput)){
alert("The first 3 characters must be letters");
}
}
while (userInput.length != 7 && regEx.test(userInput)){
}
}

Password validation by using java script regular expression contains at least two digit anywhere. It can contain special characters and letters

I need to check for password by using java script regular expression. for the password check, it should have at least two digit, it can contain special character, it has letters as well.
I believe the following script should do the trick. If you're going to use this script, you'll need a button that calls the function with the inputted password as its argument. I hope this helps.
var password;
var passValid = false;
function checkPass(enteredPass) {
if(enteredPass.length >= 2) { //Makes sure that the entered password is equal to or higher than the minimum length
var numsFound = 0;
var letterFound = false;
var splitPass = enteredPass.split("");
for(i=0; i < enteredPass.length; i++) { //Checks all characters for letters and numbers
if(splitPass[i] >= 0 && splitPass[i] <= 9) {
numsFound++;
} else if(splitPass[i] >= "a" && splitPass[i] <= "z" || splitPass[i] >= "A" && splitPass[i] <= "Z") {
letterFound = true;
};
if(numsFound >= 2 && letterFound) { //Successful scenario
password = enteredPass;
console.log("the entered password is valid, updated password successfully");
return;
};
};
};
console.log("the entered password is invalid, update cancelled"); //Error scenario
};
I have framed regular expression, which should check for alphanumeric along with set of special characters and find at least 2 digits.
\(?=(?:[^0-9]*[0-9]){2,})[a-zA-Z0-9!#$*\-.\/?_&,]{1,}\
I took the help of https://regex101.com site for reference & testing.

jQuery Tools Validator - regex test - exclude just letters

i'm trying to validate a field to include everything except letters but the following only works on the first character i enter. So if i enter '123a' the test method returns true.
$.tools.validator.fn("input#Phone", "Please enter a valid phone number.", function(input, value) {
var pass;
var rgx = /[^a-z]/gi;
if ( rgx.test(value)
|| (value == "")
|| (value == $(input).attr("placeholder"))) {
$(input).removeClass("invalid");
pass = true;
} else {
$(input).addClass("invalid");
pass = false;
}
return pass;
}
You're only matching against a single character.
/^[^a-z]$/i
This ensures that the entire string is non-letters.
for only numeric:
RegExp(/^[^a-zA-Z]$/i)
for phone number you can use
RegExp(/^[0-9 -()+]{6,20}$/i)

How do I validate a phone number with javascript?

Would someone a little smarter than myself be able to help me with this function? Its purpose is to validate a text input in a form, a phone number field that will only accept 0-9, dash and dot. The HTML calls the function fine.
function validateFeedback() {
var phone = document.getElementById("phone");
var validNumber = "0123456789.-";
for (i = 0; i < phone.length; i++); {
if (validNumber.indexOf(phone.charAt(i)) == -1); {
alert("You have entered an invalid phone number");
return false;
}
}
return true;
}
Thanks so much for any help.
Regular expressions should help ;)
I'm sorry I haven't tried to run this code, but it should be OK.
function validateFeedback(){
var phone = document.getElementById("phone");
var RE = /^[\d\.\-]+$/;
if(!RE.test(phone.value))
{
alert("You have entered an invalid phone number");
return false;
}
return true;
}
try like this:
function validateFeedback()
{
var phone = document.getElementById("phone");
var validNumber = "0123456789.-";
for(i = 0; i < phone.length; i++) {
if(validNumber.indexOf(phone.charAt(i)) == -1) {
alert("You have entered an invalid phone number");
return false;
}
}
return true;
}
there are ; out of place ...
I think you should use a regex to do this. Something link this:
function validateFeedback() {
var phone = document.getElementById("phone").value;
var reg = new RegExp("[0-9 .-]*");
return reg.test(phone);
}
If the text input is in a form, you can reference it more directly using the form id and the element id:
var phone = document.<formId>.phone;
What you want to test is the value of the element, so you need:
var phone = document.<formName>.phone.value;
Since the function is probably called from a submit listener on the form, you can make things more efficient using:
<form onsubmit="return validateFeedback(this);" ...>
It also seems to me that a phone number has only digits, not "-" or "." characters, so you should only test for digits 0-9.
So the function can be like:
function validateFeedback(form) {
var phoneValue = form.phone.value;
// Use a regular expression to validate the value
// is only digits
if (/\D/.test(phoneValue) {
// value contains non-digit characters
// advise user of error then
return false;
}
}
you may want to test that the length is reasonable too, but note that phone numbers in different places are different lengths, depending on the location and use of area or country codes, and whether the number is for a mobile, landline or other.
I would prefer to use regular expressions for something like this.
Please look at my modified version of your function which should work in all major browsers without any framework.
function validateFeedback() {
// Get input
var phone = document.getElementById("phone"),
// Remove whitespaces from input start and end
phone = (phone || '').replace(/^\s+|\s+$/g, ''),
// Defined valid charset as regular expression
validNumber = "/^[0123456789.-]+$/";
// Just in case the input was empty
if (phone.length == 0) {
// This depends on your application - is an empty number also correct?
// If not, just change this to "return false;"
return true;
}
// Test phone string against the regular expression
if (phone.match(validNumber)) {
return true;
}
// Some invalid symbols are used
return false;
}
Try this one
function validateFeedback(value) {
var length = value.length;
chk1="1234567890()-+ ";
for(i=0;i<length;i++) {
ch1=value.charAt(i);
rtn1=chk1.indexOf(ch1);
if(rtn1==-1)
return false;
}
return true;
}
function phonenumber(inputtxt)
{
var phoneno = /^\d{10}$/;
if((inputtxt.value.match(phoneno))
{
return true;
}
else
{
alert("message");
return false;
}
}

Check If only numeric values were entered in input. (jQuery)

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] : '');
}

Categories

Resources