Validate input with regular expression for universal alphabets in javascript - javascript

I have a form validator by AntonLapshin where I'm trying to validate a non-empty input field which can only take alphabets, space, - and '. The alphabets can be a-z, A-Z and europian letters æÆøØåÅöÖéÉèÈüÜ, etc. See this for more details.
Here is what I am doing:
method : function(input) {
return input.value !== ''
&& input.value === /^[a-zA-Z'\- \u00c0-\u017e]+$/
}
Here, it should match: Åløæ-Bond Mc'Cool
But fail: 123-Bond Mc'C#o!
When I run ^[a-zA-Z'\- \u00c0-\u017e]+$ in regex tester, It works absolutely fine, but in my script, it is not validating and throws an invalid input error.
What am I doing wrong?

I prefer to use RegExp. You also need to do return pattern.test(input)
This will work :)
var test1 = "Åløæ-Bond Mc'Cool";
var test2 = "123-Bond Mc'C#o!";
var pattern = new RegExp(/^[a-zA-Z'\- \u00c0-\u017e]+$/);
function regextest(input) {
return input !== '' && pattern.test(input)
}
console.log(regextest(test1))
console.log(regextest(test2))

modify your function to test with regex
var pattern = /^[a-zA-Z'\- \u00c0-\u017e]+$/
var method = function(input) {
return input !== '' &&
pattern.test(input)
}
//your sample strings
console.log(method("Åløæ-Bond Mc'Cool"))
console.log(method("123 - Bond Mc 'C#o!"))

I figured out a simpler solution for my question:
method : function(input) {
return input.value !== '' && /^[a-zA-Z'\- \u00c0-\u017e]+$/.test(input.value)
}
The problem was, after the && operator, I was checking for the input value (that’s wrong in regex check) instead of Boolean value.
This solution works perfectly and creates no confusion.

Related

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

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

CoderByte SimpleSymbols challenge: pattern recognition in strings (using RegExp)

The problem:
Have the function SimpleSymbols(str) take the str parameter being passed and determine if it is an acceptable sequence by either returning the string true or false. The str parameter will be composed of + and = symbols with several letters between them (ie. ++d+===+c++==a) and for the string to be true each letter must be surrounded by a + symbol. So the string to the left would be false. The string will not be empty and will have at least one letter.
My code:
function SimpleSymbols(str) {
var arr = str.match(/[\+][a-zA-Z][\+]/g);
var total = str.match(/[a-zA-Z]/g);
if(arr === null || total === null)
return false;
else if(arr.length >= 1 && arr.length === total.length)
return true;
else
return false;
}
All the test cases except for these three pass:
-"+z+z+z+"
-"2+a+a+"
-"+z+z+==+a+"
What I've done: checked the other question on this problem. Tried another solution using regex but it had issues with input like "b".
I think the problem has something to do with when the pattern is "+char+char+" since a lot of the other test cases are like "++char+==+char+=="

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

Regex for a valid numeric with optional commas & dot

i am trying only to allow numerals and special chars like '.' and ',' to be allowed in my text string. for that i have tried following code
var pattern = /[A-Za-z]/g;
var nospecial=/[\(#\$\%_+~=*!|\":<>[\]{}`\\)';#&?$]/g;
if (!ev.ctrlKey && charCode!=9 && charCode!=8 && charCode!=36 && charCode!=37 && charCode!=38 && (charCode!=39 || (charCode==39 && text=="'")) && charCode!=40) {
console.log(text);
if (!pattern.test(text) && !nospecial.test(text)) {
console.log('if');
return true;
} else {
console.log('else');
return false;
}
}
but not getting the desired output. tell me where i am wrong.
Forget trying to blacklist, just do this to allow what you want:
var pattern = /^[0-9.,]*$/;
Edit: Also, rather than just checking for numbers, commas, and dots. I'm assuming something like this do even more than you were hoping for:
var pattern = /^(0|[1-9][0-9]{0,2}(?:(,[0-9]{3})*|[0-9]*))(\.[0-9]+){0,1}$/;
Demo
So why don't you try /^[0-9,.]*$/ instead of negating the test?
You can try this:
/([0-9]+[.,]*)+/
It will matche number with or withot coma or dots.
^(?!.*[^0-9.,\n]).*$
Not sure of what you mean by efficient but this fails faster though it takes long to match correct string.See demo.
http://regex101.com/r/aK2zV7/1
You could also just use the solution from this answer:
parseFloat(text.replace(',',''));

Categories

Resources