Why this regular expression return false? - javascript

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()) {

Related

How to make an if statement with conditions that include "and" in javascript

I am trying to make a password and confirmation password match, without them both being just left blank.
I would like to add in this part about the password fields not being able to be left blank, in the if statement, by saying the passwords have the same value, and these values are not blank.
The function worked fine when it was just the if statement, saying that the passwords had to match in order for the welcome alert to come up, and have found that the and symbol in javascript is && but i don't know how to use it in the context.
var check = function() {
if (document.getElementById('psw').value ==
document.getElementById('psw-repeat').value)
&&
(document.getElementById('psw').value) != ""
&&
(document.getElementById('psw-repeat').value) != "" }
else {
alert("passwords do not match")
}
}
I would expect this code to say that the passwords haven't been filled out, if they haven't, to say welcome if the password and confirmation password match, and to say the passwords do not match if they do not match.
I'm not sure what I've done wrong but would love if anyone could help.
:))
You're not closing the whole if statement with ()
Okay, best way to do conditions it like following.
why best
optimized, you don't need to get values from dom again and again for
condition checking
easy to read if condition.
If code is not readable then not the best code
So always try to break the conditions
function() {
var password = document.getElementById('psw').value;
var password_repeat = document.getElementById('psw-repeat').value;
if (password == password_repeat && password != "" && password_repeat != "")
{
// code ..........
}
else
{
alert("passwords do not match")
}
}
For better code checking and styling, use some IDEs like VSCode Atom Bracket
but personally I like the VSCode
The only real problem is out-of-place parentheses and curly braces, but this way adds a couple of improvements beyond those simple fixes.
// Select HTML elements
const psw = document.getElementById("psw");
const pswRepeat = document.getElementById("psw-repeat");
const checkBtn = document.getElementById("checkBtn");
// Listen for button clicks
checkBtn.addEventListener("click", check);
// Validate passwords
function check(){
if(pswRepeat.value === psw.value && psw.value != ""){
// We know they are the same, and psw is not empty (so neither is pswRepeat)
alert("good");
}
else{
alert("passwords do not match");
}
}
<input id="psw" />
<input id="psw-repeat" />
<button id="checkBtn">Check</button>
You forgot to close the parenthesis.
You need better indentation to detect these kinds of problems early and some separation of logic to keep the code readable.Something like this :
var check = function() {
if (isValid()) {
//Welcome here
} else {
alert("passwords do not match")
}
}
function isValid() {
var psw = document.getElementById('psw').value;
var repeatPsw = document.getElementById('psw-repeat').value;
//Logic to check for password
if (psw == repeatPsw &&
psw != "" &&
repeatPsw != ""
)
return true;
return false;
}

Validate number formats in a contact form (javascript)

I have a function to validate phone number in a contact form, but i need to be able to put in "xxx xxx xxxx" for example, and not just "xxxxxxxx"
The number format should be:
xxx xxx xxxx
xxx-xxx-xxxx
xxx.xxx.xxxx
function validatePhone() {
var phone = document.getElementById("phone").value;
if (phone.length == 0) {
var w = document.getElementById("phoneError").textContent;
alert(w);
return false;
}
if (phone.length != 10) {
var r = document.getElementById("phoneError").textContent;
alert(r);
return false;
}
// THIS IS NOT WORKING
if (
!phone.match(/^[0-9]{10}$/) ||
!phone.match(/^\d{3}-\d{3}-\d{4}$/) ||
!phone.match(/^\d{3}.\d{3}.\d{4}$/)
) {
var t = document.getElementById("phoneError").textContent;
alert(t);
return false;
}
}
Two things: First, you are mixing up AND and OR:
if (
!phone.match(/^[0-9]{10}$/) ||
!phone.match(/^\d{3}-\d{3}-\d{4}$/) ||
!phone.match(/^\d{3}.\d{3}.\d{4}$/)
) {
As soon as one of the conditions fails, it will return false (which is basically always). You want this if to apply, when none of the expressions matches, e.g. when all of them are false. Therefor, you have to use && instead of ||. Not a AND not b AND not c.
Second: your 3rd regex is a bit off: . means "any character", so this regex would also match "123x123y1234". You need to escape the dot with a backslash: /^\d{3}\.\d{3}\.\d{4}$/
Also, you can improve this code significantly. You have 5 conditions, which could all be handled in one (if you want to allow the input of "123.123 234", otherwise you will have to do it using 3 regex). And for just checking if a regex matches a string, you maybe should use test(), because it is just slightly faster (it won't matter in your case, but just out of principle).
You can reduce your code to:
if (/^\d{3}[\s-.]\d{3}[\s-.]\d{4}$/.test(document.getElementById("phone").value) === false) {
alert (document.getElementById("phoneError").textContent);
return false;
}

Javascript Eval() thinks first value is a function

I am writing a function that will evaluate expressions in an input field and return the sum.
Currently is working but I am running into an error that I just cannot figure out. Here is my code in Plunker.
function linkFunction(scope) {
var PO = 10;
scope.value = PO;
scope.result = '';
scope.Evaluate = function (input) {
if (input.match(/[a-zA-Z]/g) != null) { //to check if user has inputted a letter between a-z, case sensitive.
return alert("You must only use numbers, not letters")
} else if (input.match(/[!"^£$&[{}\]?\\##~<>_'|`¬:;,=]/g) != null) { //to check if user has inputted a special symbol
return alert("You must only use the symbols specified")
} else if (input.match(/\.\d*\.+/g) != null) { //to check if user has inputted a doubled decimal eg 10.2.2
return alert("You can only use 1 decimal point")
} else if (input.match(/\.{2,}/g) != null) {//to check if user has inputted a two decimals eg 10..1
return alert("You cannot put two decimals one after another")
}
// if (input.match(/\d*\(\d\W\d\)/g) != null){
// }
var percentPattern = /[0-9]*\.?[0-9]+%/g;
var expressionResults = input.match(percentPattern);
if (scope.enablePercentage) { //if parameter = 1, then do this code.
if (expressionResults != null) { //if user has entered into the input field
if (expressionResults.length > 1) { //if you user has finished the RegEx (%, is the end of the RegEx, so code will think its the end of the array, therefore you cannot add another %)
return alert("Too many % values");
} else {// user has met all requirements
var percentageValue = parseFloat(expressionResults) * PO / 100;
input = input.replace(expressionResults, percentageValue);
}
}
} else if (expressionResults != null) { //if parameter = 0, then do this code. Parameter is off, but user has entered percentage
return alert("You cannot use %");
}
scope.result = eval(input);
}
}});
If you write 10(5+3) it gives you an error
TypeError: 10 is not a function
Obviously if a user ran this code they would expect to see the value 80.
Eval thinks that 10() is a function.
Does anyone know how to fix this problem. Thanks
eval expects you to pass it JavaScript, not algebra.
If you want to multiply two values together then you must use a Multiplicative Operator.
10 * (5+3)

How to do email address validation using Javascript (without JQuery)? [duplicate]

This question already has answers here:
How can I validate an email address in JavaScript?
(79 answers)
Closed 7 years ago.
I'm trying to do an email address validation for an input text field, however, it must only submit if the entry is not null and has the # char in it
Example 1 is the one that works, however, it excludes the need for the # char
function emailvalidation() {
var x=document.forms["input"]["email"].value;
if (x==null || x=="") {
alert("Input email address, please!");
return false
}
Example 2 which does not work, but is how I imagine it would be written
function emailvalidation() {
var x=document.forms["input"]["email"].value;
var email = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if (x<>null || x<>"" && x.value.match(email)) {
alert("Input email address, please!");
return true
} else {
alert("Input email address, please!");
return false
}
}
Anyone have any ideas? Thank you though, preferably without JQuery! Thanks!
Another email validation.
function isValidEmailAddress(emailAddress) {
var pattern = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))#((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i);
return pattern.test(emailAddress);
};
You have a couple of logical problems in your solution.
Firstly, the condition is that x is not null and x is not an empty string and x matches the pattern.
Secondly, <> is the wrong comparator for javascript; use != or !==.
Thirdly, as pointed out by putvande x is already the element's value, so x.value.match() is probably causing you issues.
function emailvalidation() {
var x = document.forms["input"]["email"].value;
var email = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if (x !== null && x !== "" && x.match(email)) {
return true;
} else {
alert("Input email address, please!");
return false;
}
}
Thank you all for this! The solution was a mixture of all of the answers! Though, here is the final solution! Needed a new reg expression and !==
Thank you all though, from a JS beginner, it is really appreciated
function emailvalidation() {
var x=document.forms["input"]["email"].value;
var email = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if (x !== null && x !== "" && x.match(email)) {
return true
} else {
alert("Input email address, please!");
return false
}
}
Based on your first script and requirements, one solution without regex, and one with.
Note that a text-inputfield only returns strings.
Email-addresses must have something before the #, so we check if an # appears after the first character (using indexOf we don't require a regex). Also, if we have found the # that means the string was not empty!!
If the # is at the same position as the last # and this position is smaller then the total string-length, this gives us a true or false value, which we can instantly return.
If none of the three conditions is met, then we alert our error-message. alert returns undefined (which in itself coerces to false in javascript, but) which we force to a boolean false using double not !! and return that value.
The second example follows the same logic, but uses a regex.
function emailvalidation(){ //without regex
var s=document.forms.input.email.value
, x=s.indexOf('#');
return( x>0 && x===(x=s.lastIndexOf('#')) && x<s.length-1
) || !!alert("Input email address, please!");
}
function emailvalidation(){ //with regex
return /^[^#]+#[^#]+$/.test(document.forms.input.email.value) || !!alert("Input email address, please!");
}
<form name="input">
<input name="email" type="text" />
</form>
<button onclick="alert(emailvalidation())">test</button>
Final note, it's good that you are liberal in accepting email-addresses, since trying to do a good job in regex is long and difficult, see for example this regex: http://www.ex-parrot.com/pdw/Mail-RFC822-Address.html
There is simply no 100% reliable way of confirming a valid email address other than sending an email to user and and waiting for a response. See also https://softwareengineering.stackexchange.com/questions/78353/how-far-should-one-take-e-mail-address-validation
If you do try to regex 'valid email-addresses' then inform your employer that you are going to cost him business/clients/cash!!!

Javascript Replace - Regular Expression

I need to replace a code example: OD3 - The first must always be alpha character, 2nd alphanumeric and the last must always be numeric. What's the regular expression to check and replace the first and regulate the rest to enter correctly? A user could enter in the number 0 instead of the letter O, so I want to correct it immediately...
this is what I have so far: onkeyup="this.value=this.value.replace(/[^a-zA-z]/g,'')
First, I'd suggest just indicating the error to a user instead of replacing the values. Something like
oninput="if (! /^[a-z][a-z0-9]\d$/i.test(this.value) ) displayMessage('incorrect code');"
If you definitely have to replace the value on the fly, you could do somthing like that:
oninput='validateValue()';
...
function validateValue() {
var val = this.value;
if (! /[a-z]/i.test(val[0]) this.value = '';
else if (! /[a-z0-9]/i.test(val[1]) this.value = val.slice(0,1);
else if (! /\d/.test(val[2]) this.value = val.slice(0,2);
}
Better have like this.
onkeyup="testRegex(this.value)";
It is not .replace() it is .test()
function testRegex(value) {
if(value.test(/[^a-zA-z]/g)) {
alert("Please enter correct value");
return false;
}
}

Categories

Resources