Scan string for special characters and alphabets - javascript

I have a textbox which accepts time (max of 5 chars) in the format hh:mm or hhmm. Pls tell me a way I can just scan the string entered in the textbox, for special characters and alphabets? [If the string entered has these chars or alphabets, then an alert is displayed('Pls enter a valid time')] I tried the str.match and str.indexOf methods but it doesn't seem to help.
<script type='text/javascript'>
function clocks(){
var clk = document.getElementById('TIME').value;
var ampm = document.getElementById('AMPM').value;
var iChars = "!##$%^&*()+=-[]\\\';,./{}|\":<>?";
for (var i = 0; i < 5; i++) {
if (iChars.indexOf(clks.charAt(i)) != -1) {
alert ("Pls enter a valid time");
return false;
}
}
.....}
</script>

How are you using string.match()? This should work:
<script type='text/javascript'>
function clocks(){
var clk = document.getElementById('TIME').value;
var ampm = document.getElementById('AMPM').value;
if (clk.match(/[^0-9:]/)) {
alert("Please enter a valid time");
}
// or, an even more precise regex
if (!clk.match(/^\d+:\d+$/)) {
alert("Please enter a valid time");
}
.....}
</script>
The first regex match should check for anything that is NOT a digit or the ':' character, and raise an alert if it finds anything. The second one will match any string that starts with one or more digits, then a ':' character, then one or more digits, then the end of the string (which is the format you're trying to match).

Related

Finding the type of the first letter of the value of a JavaScript variable, whether it is a letter, a number or a special character

I've a variable named var text = 'Saif'
So how can I check the first character of this value (S) is a letter, number or special character??
I've already tried with the code bellow -
var text = 'Saif'
var char = /[A-Z]/g
var num = /[0-9]/g
if (text.match(char)) {
console.log("The string starts with Letter")
} else if (text.match(num)){
console.log("The string starts with Number")
} else {
console.log("The string starts with Special character")
}
It's working fine with the condition of letter and number. But I can't being able to find the special character instead of letter or number.
How can I do that?
First of all, char is a reserved word in JavaScript - best not to use it in your variable names.
Secondly, if you want to test a pattern but not actually retrieve the match, use test() rather than match().
Thirdly, your current patterns don't enforce only the first character of the string; they allow any character within it.
if (/^[a-z]/ig.test(text))
console.log("The string starts with Letter")
else if (/^\d/.test(text))
console.log("The string starts with Number")
else
console.log("The string starts with Special character")
Try this:
var text = 's2Saif'
var char = /^[A-Z]/g
var num = /^\d/g
if (text.match(char)) {
console.log("The string starts with Letter")
} else if (text.match(num)){
console.log("The string starts with Number")
} else {
console.log("The string starts with Special character")
}
Does Letter contain lowercase character? If so, let var char = /^\w/g;
Give this a try:
var format = /[ `!##$%^&*()_+\-=\[\]{};':"\\|,.<>\/?~]/;
// This ↓ method will return true or false value.
if (format.test(text)) {
console.log("The string starts with Special character");
}

javascript program verifies username w/ eight characters, one numeric and beginning with a letter. What am I doing wrong?

<html>
<body>
<script type="text/javascript">
// Verify username has eight characters, contains a letter in the first part and
// at least one number
// Declare variables and constants
var username; // username entered by user
var charAny; // text character identified in username
var anyNum = false; // digit variable used to detect whether the username has one or not
var index; // index loop variable
var BR = "<br />"; //break
var ES = ""; //space
// Display program requirements for the username requested
document.write("We'll begin helping you select a username" + BR);
document.write("Your username must have at least 8 characters," + BR);
document.write(" start with a letter, and contain at least 1 numeric character." + BR);
username = prompt("Please enter your username: ", ES);
// Check for length of username
while (username.length < 8) {
document.write("Your username must be at least 8 characters long." + BR);
username = prompt("Please enter your username: ", ES);
}
// Check that first character is a letter
// Substring function has three arguments: string, starting position, and ending position
charAny = username.substr(0, 1);
while (charAny !== isLetter()) {
document.write("The first character of your username must be a letter." + BR);
username = prompt("Please enter your username: ", ES);
}
// Check that there's at least one digit in the username
while (anyNum !== false) {
// Check each character, set anyNum to true if a digit
for (index = 1; index < username.substr(index, index); index++) {
anyNum = username.substr(index, index);
if (isNumeric(charAny)) {
anyNum = true;
}
}
// If anyNum is false there were no numerics
if (anyNum !== true) {
document.write("Your username must include at least 1 digit." + BR);
username = prompt("Please enter your username: ", ES);
}
}
// Thank the user and end the program
document.write("Thank you! Your new username is: " + username);
</script>
</body>
</html>
The problem is that the username still verifies as long as there are eight characters, even when there is no numeric present. What am I doing wrong that it skips verifying numeric?
I've made edits to make sure that the variables are correct
If the username contains all non digit, anyNum is never set to true.
In the Check Each Character loop you assign a substring of username to the anyNum variable. So if the username consists of all non digits, the variable will never have a boolean (true/false) value.
Furthermore I have the folllowing remarks/findings:
Check Each character loop: assign the substring to charAny and not to anyNum.
Check Each character loop: assign 1 character to charAny username.substr(index, 1).
Check Each character loop: check in the while clause on username.length.
use for the ceck of the first character if instead of while
General: you can also use a regular expression to check the format of the username (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions).
It's hard for me to test your code, since document.write is disallowed in JSFiddle. In general you don't want to use document.write anyway. Another tip, you can treat Javascript strings as arrays.
Here is a sample function that does what you're asking.
function checkUsername(test){
var good = true;
if (!test[0].match(/[a-z]/i)) good = false; // first character is not a letter
if (test.length < 8) good = false; // less than 8 characters
if (test.match(/\d+/g) == null) good = false; //contains no numbers
return good;
}
<html>
<body>
<script type="text/javascript">
// Verify username has eight characters, contains a letter in the first part and
// at least one number
// Declare variables and constants
var username; // username entered by user
var anyNum = false; // digit variable used to detect whether the username has one or not
var index; // index loop variable
var BR = "<br />"; //break
var ES = ""; //space
// Display program requirements for the username requested
//document.write("We'll begin helping you select a username" + BR);
//document.write("Your username must have at least 8 characters," + BR);
//document.write(" start with a letter, and contain at least 1 numeric character." + BR);
username = prompt("Please enter your username: ", ES);
// Check for length of username
if (username.length < 8) {
document.write("Your username must be at least 8 characters long." + BR);
username = prompt("Please enter your username: ", ES);
}
// Check that first character is a letter
// Substring function has three arguments: string, starting position, and ending position
charAny = username.substr(0, 1);
if (!isLetter(charAny)) {
document.write("The first character of your username must be a letter." + BR);
username = prompt("Please enter your username: ", ES);
}
// Check each character, set anyNum to true if a digit
for (index = 1; index < username.length; index++) {
charAny = username.substr(index, 1);
if (isNumeric(charAny)) {
anyNum = true;
}
}
// If anyNum is false there were no numerics
if (anyNum !== true) {
document.write("Your username must include at least 1 digit." + BR);
username = prompt("Please enter your username: ", ES);
}
// Thank the user and end the program
document.write("Thank you! Your new username is: " + username);
function isLetter(character) {
return true;
}
function isNumeric(character) {
return ("01234567890".search(character) > -1);
}
</script>
</body>
</html>
I was instructed to approach the problem as such:
var char1 = myPassword.substr(0,1);
if(isNaN(char1) == true)
isFirstLetterACharacter would be a boolean variable that you personally assign, and then set as a flag for the loop to end.
This is what my pseudocode would look like. Notice I kind of brute forced the thing. I don't have to check every character on a sixteen character password, just the first 8 will suffice.
function passwordChecker(pass1)
{
two conditions must be met for the loop to end: first letter is a character must be true AND at least one letter starting at character two is numeric must also be true.
inside that while loop:
if pass1.length is greater than or equal to 8
make eight characters, char 1 through char8.
if char1 is not a number, then firstletterisacharacter is true. else, tell the user so.
if char2 is a number (the opposite of not a number), then at least one letter starting at character two is numeric will be true.
ask the same question over and over again for chars 3 through 8.
all else, say the password is not long enough.

javascript validation for special character's index/position

I have input as 23 digit key from input box which will be separated by '-'.
E.g: XXXXX-XXXXX-XXXXX-XXXXX
This is expected format means, 5 digit followed by -(hyphen).
Problem:
User can input any data/wrong format, like XXX-XXXXX-XXXXX-XXXXXXX, in this case index of hyphen is invalid. How can I valided the index of hyphen?
I tried:
if((prd_len==23) && (n!=-1))
{
var indices = [];
for(var i=0; i<prd_id.length;i++)
{
if (prd_id[i] === "-")
{
indices.push(i);
}
}
for(var x=0;x<indices.length;x++)
{
if((indices[x]!=5) || (indices[x]!=11) || (indices[x]!=17))
{
$('#msgErr1').text('Please enter valid key.');
flag=1;
}
}
}
where prd_len=length of the accepted input from user.
Try regular expressions
if(input.match(/^(\d{5}-){3}\d{5}$/))
everything is OK
This expression basically reads "five digits and a dash - three times, then five digits". For further reference see
http://www.regular-expressions.info/
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
As thg435 said, but more human-readable :-)
var correct = input.match(/^\d\d\d\d\d-\d\d\d\d\d-\d\d\d\d\d-\d\d\d\d\d$)

javascript for checking alphabets from a string

I have a string which is of format 245545g65.
var value = "245545g65"
var last3Letters = value.substring(7,9); // abc
Now I want to validate whether the last three letters contains only alphabets, if it is alphabet , i want to alert it.how to alert g?
how do i do this?
assuming that "contains only alphabets" means the last three characters are a combination of the letters a-z:
var str = '245545g65';
if (/[a-z]{3}$/.test(str)){
// last three characters are any combinations of the letters a-z
alert('Only letters at the end!');
}
you can use RegEx and compare length
var re = new RegExp("[^0-9]*", "g");
var newlast3Letters =last3Letters.replace(re,"");
if(newlast3Letters.length!=last3Letters.length)
{
alert("not all alphabets");
}
else
{
alert("all alphabets");
}
you can use isNaN to check weather s string is number
if (!isNan(last3Letters))
alert(last3Letters + ' is number.')
else
alert(last3Letters + ' is not number.')
You can also do this:
var value = "245545g65"
if(value.slice(value.length-3).search(/[^a-z]/) < 0) {
alert("Just alphabets");
} else {
alert("Not just alphabets");
}
Easy:
var alpha = /^[A-z]+$/;
alpha.test(last3Letters);
This will return a boolean (true/false). Stolen from here.

Guide line for Regex to validate input

i want to validate a input by regex. if user enter any character with in a to z or A to Z then it will not accepted but if user enter + sign or bracket or any digit then it will be accepted. i use the regex but it did not work as per my requirement.
var regEx = '/^[A-Za-z]*$/';
if (flag) {
var val = jQuery.trim($("input[id*='txtfphone']").val())
if (val.match(regEx)) {
if (_AdjustHeight == 0) {
$(".ui-dialog").animate({ height: '+=' + dialog_loader.height + 'px' }, 600, function () {
_AdjustHeight = 1;
$('#feed_loader').fadeIn('slow').html('<span>' + dialog_Msg.Invalid_Phone + '</span>');
$("input[id*='txtfphone']").focus()
});
}
else if (_AdjustHeight == 1) {
$('#feed_loader').fadeOut('slow', function () {
$('#feed_loader').html('<span>' + dialog_Msg.Invalid_Phone + '</span>');
}).fadeIn('slow');
$("input[id*='txtfphone']").focus()
}
flag = false;
return false;
}
}
so help me with right regex.
it will be accepted if user enter data like
+913325806589
+91 33 25806589
913325806589
91 33 25806589
91 (33) 25806589
+91 (33) 25806589
but if user enter any alphabet as a input then it will not be accepted. like
aaab
+a913325806589
+91332a5806589
+91332a5806589b etc
a to z any character will not be accepted. thanks
does this one meets your need?
var regEx = /^\+?\d+[\d\s]*(\s*\(\d+\)\s*\d*)*$/ //no quote !!
for your
var regEx = '/^[A-Za-z]*$/'
you have defined the regEx to a string, so it won't take any effect.
The regrex you are using is anchored at both the beginning and end, which means it will only match when the input contains only letters. It would not, for example, match "12a".
It also fails to check for all of the other invalid characters you haven't mentioned... !£## etc.
It would be better to use a regex that matches what you do want, and then see if the input fails to match.
From your description and examples, this should match valid input:
/^\s*\+?[\d\s]*(\([\d\s]+\)?)[\d\s]*$/
You then need to negate your match test:
if (!val.match(regEx)) {

Categories