Regular expression begin in javascript - javascript

I have an input text where user can write string.
I want to have an regular expression in javascript which check if the string starts with three characters FSM.
If the user write another string which doesn't start with FSM, this string was automatically remove and give the error message
Example:
FSMLERTE True
FSMAMAMA True
SFMABNE false et remove this content in the input
I do this but it's doesn't work
var input22Regex= /^[a-z]$/;
if(inputtxt.value.match(inputRegex)) {
return true;
} else {
inputtxt.value = '';
alert("String must start with FSM");
return false;
any idea ?

Try the following:
const testRegex = /^FSM/;
function testString(str) {
if (testRegex.test(str)) {
return true;
} else {
console.log("String must start with FSM");
return false;
}
}
console.log(testString('FSMLERTE')); // true
console.log(testString('FSMAMAMA')); //true
console.log(testString('SFMABNE')); // false

You can use startsWith
if(inputtxt.value.startsWith('FSM')) {
return true;
} else {
inputtxt.value = '';
alert("String must start with FSM");
return false;
}

I think your regex should look like this
/^FSM(.)*/g

You should use /^FSM[A-Z]*/ which will match all inputs that start with FSM and 0 or more capital letters following it. If you want it to be case-insensitive, you can use this instead: /^FSM[A-Z]*/i
var input22Regex = /^FSM[A-Z]*/;
if (inputtxt.value.match(inputRegex)) {
return true;
} else {
inputtxt.value = '';
alert("String must start with FSM");
return false;
}

You can try this regex
FSM[a-zA-Z0-9]+
Demo

Related

Why this regular expression return false?

i have poor eng, Sorry for that.
i'll do my best for my situation.
i've tried to make SignUpForm using regular expression
The issue is that when i handle if statement using the regular expression
result is true at first, but after that, become false. i guess
below is my code(javascript)
$(document).ready(function () {
var idCheck = /^[a-z]+[a-z0-9]{5,19}$/g; // more than 6 words
var pwCheck = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$/; // more than 8 words including at least one number
var emCheck = /^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/; // valid email check
var signupConfirm = $('#signupConfirm'),
id = $('#id'),
pw = $('#pw'),
repw = $('#repw'),
email =$('#email');
signupConfirm.click(function () {
if(id.val() === '' || pw.val() === '' || email.val() === ''){
$('#signupForm').html('Fill the all blanks');
return false;
} else {
if (idCheck.test(id.val()) !== true) {
$('#signupForm').html('ID has to be more than 6 words');
id.focus();
return false;
} else if (pwCheck.test(pw.val()) !== true) {
$('#signupForm').html('The passwords has to be more than 8 words including at least one number');
pw.focus();
return false;
} else if (repw !== pw) {
$('#signupForm').html('The passwords are not the same.');
pw.empty();
repw.empty();
pw.focus();
return false;
}
if (emCheck.test(email.val()) !== true) {
$('#signupForm').html('Fill a valid email');
email.focus();
return false;
}
}
})
});
after id fill with 6 words in id input, focus has been moved to the password input because the condition is met.
but after i click register button again, focus move back ID input even though ID input fill with 6 words
i've already change regular expression several times. but still like this.
are there Any tips i can solve this issue?
I hope someone could help me.
Thank you. Have a great day
Do not use the global flag on your regexes. Your code should be:
var idCheck = /^[a-z]+[a-z0-9]{5,19}$/;
When you match with the /g flag, your regex will save the state between calls, hence all subsequent matches will also include the previous inputs.
use
var idCheck = /^[a-z]+[a-z0-9]{5,19}$/
removing the g flag
and modify the line
else if (repw.val() !== pw.val()) {

Remove punctuation and spaces from String

The function compress() would accept a sentence and return a string with all the blanks and punctuation removed. This function must call isWhiteSpace() and isPunct().
I've already done the functions to call, but I don't know what's missing from my js code to make it call the functions.
function compress(sent) {
var punc = "; : . , ? ! - '' "" () {}";
var space = " ";
if (punc.test(param)) {
return true
} else {
return false
}
if (space.test(param)) {
return true
} else {
return false
}
isWhiteSpace(x);
isPunct(x);
}
This function must call isWhiteSpace() and isPunct().
So you already have two functions which I assume return true when the passed character is either whitespace or a punctuation mark. Then you need not and should not duplicate this functionality by implementing a duplicate regex based text for whitespace and punctuation in your code. Keep it DRY - don't repeat yourself.
A compress function based on these two functions would look as follows:
function isWhiteSpace(char) {
return " \t\n".includes(char);
}
function isPunct(char) {
return ";:.,?!-'\"(){}".includes(char);
}
function compress(string) {
return string
.split("")
.filter(char => !isWhiteSpace(char) && !isPunct(char))
.join("");
}
console.log(compress("Hi! How are you?"));
I agree that a regex test would probably the to-go choice in a real world scenario:
function compress(string) {
return string.match(/\w/g).join("");
}
However, you specifically asked for a solution which calls isWhiteSpace and isPunct.
You can leverage String.indexOf to design the isPunct function.
function isPunct(x) {
// list of punctuation from the original question above
var punc = ";:.,?!-'\"(){}";
// if `x` is not found in `punc` this `x` is not punctuation
if(punc.indexOf(x) === -1) {
return false;
} else {
return true;
}
}
Solving isWhiteSpace is easier.
function isWhiteSpace(x) {
if(x === ' ') {
return true;
} else {
return false;
}
}
You can put it all together with a loop that checks every character in a string using String.charAt:
function compress(sent) {
// a temp string
var compressed = '';
// check every character in the `sent` string
for(var i = 0; i < sent.length; i++) {
var letter = sent.charAt(i);
// add non punctuation and whitespace characters to `compressed` string
if(isPunct(letter) === false && isWhiteSpace(letter) === false) {
compressed += letter;
}
}
// return the temp string which has no punctuation or whitespace
return compressed;
}
If you return something in a function, execution will stop.
From what I can see, your function doesn't need to return anything... So you should just do this
function compress(sent) {
var punc = ";:.,?!-'\"(){} ";
var array = punc.split("");
for (x = 0; x < array.length; x++) {
sent = sent.replace(array[x], "");
}
isWhiteSpace(x);
isPunct(x);
return sent;
}

Validating phone numbers. Null is not an object

I'm doing a challenge on Freecodecamp. I'm having a problem that seems to make no sense to me.
function telephoneCheck(str) {
// if string contains a letter then return false //
var exc = /[a-z\?/]/;
// check str to see if it has anything from the //
// regex and then make it into a string. //
var excJoin = str.match(exc).join('');
// if theres something in the //
// variable(something was found with regex) //
// then return false //
if(excJoin.length > 0) {
return false;
}
// else return true //
if(excJoin === null){return true;}
}
telephoneCheck("2(757)622-7382");
Returning false is fine, however when I just want to say else {return true;} it tells me null is not an object. What's the problem?
http://freecodecamp.com/challenges/validate-us-telephone-numbers
String.prototype.match (in your code: str.match(exc)) returns null if it didn't match the regex, so then the code is equivalent to null.join(''), which is an error.
Instead, check if it's null first:
var excResult = str.match(exc);
if (excResult === null) {
// didn't match, do something
} else {
// did match, do something else
}
You must test for nullity before using the object
str.match(exc) returns null if there are no founds for the given pattern.
So your code should do this:
function telephoneCheck(str) {
// if string contains a letter then return false
var exc = /[a-z\?/]/;
//The match() method retrieves the matches when matching a string against a regular expression.
var excResult= str.match(exc);
//return false if there is a found
if(excResult != null) {
return false;
}
else{
//there is no found cause excResult == null
return true;
}
telephoneCheck("2(757)622-7382");

validating input if starts with "T" or "TP"

I have an input. I need to validate if the value starts with "T" followed by numbers or "TP" followed by numbers
Accepted values: T12345 or TP12345
My JavaScript code
var ip_value = document.getElementById('PROMASTER_NO_FW').value;
var v_first_char = ip_value.substr(0, 1);
var v_second_char = ip_value.substr(1, 1);
if (v_first_char.toUpperCase() !== 'T') {
alert('It must be start with T');
return false;
} else {
if (v_second_char.toUpperCase !== 'P' && isNaN(Number(v_second_char))) {
alert('error2');
return false;
} else {
return true;
}
}
function myFunction() {
var ip_value = document.getElementById('test').value; //'AB12345';
var v_first_char = ip_value.substr(0, 1);
var v_second_char = ip_value.substr(1, 1);
if (v_first_char.toUpperCase() !== 'T') {
document.getElementById("error").innerHTML = 'It must be start with T';
} else if (v_second_char.toUpperCase() !== 'P' && isNaN(Number(v_second_char))) {
document.getElementById("error").innerHTML = 'error2';
} else {
document.getElementById("error").innerHTML = 'no error';
}
}
It will work on blur <br />
<input type="text" id="test" onblur="myFunction()">
<span id="error">No Error</span>
I think your logic is perfect and should work fine, you just need to change:
v_second_char.toUpperCase
to
v_second_char.toUpperCase()
in last if condition
Final code will be
var ip_value = document.getElementById('PROMASTER_NO_FW').value;
var v_first_char = ip_value.substr(0, 1);
var v_second_char = ip_value.substr(1, 1);
if (v_first_char.toUpperCase() !== 'T') {
alert('It must be start with T');
return false;
} else {
if (v_second_char.toUpperCase() !== 'P' && isNaN(Number(v_second_char))) { //change in this line
alert('error2');
return false;
} else {
return true;
}
}
Or for the short line of code you can use the regular expression as shown in above answers.
You can use regular expression to achieve your scenario.
var reg = new RegExp(/^TP?[0-9]+$/)
if((string).match(reg))
return true
else
return false
The condition in the if statement can also be used to retrieve the match string from the original string provided.
Pattern matching against a regular expression would be the best thing to use here. Assuming you are returning true if and only if ip_value is a 'T' or 'TP' followed by at least one number:
var ip_value = document.getElementById('PROMASTER_NO_FW').value;
var pattern = new RegExp(/^TP?\d+$/);
return pattern.test(ip_value);
/^TP?\d+$/ is the regular expression pattern or regex for short - if you're not familiar with regexes, a good starting point in the context of Javascript is the MDN Regular Expressions Guide.

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;
}
}

Categories

Resources