Javascript Replace - Regular Expression - javascript

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

Related

Validate input with regular expression for universal alphabets in 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.

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

Declare variable in js

I have a problem using quotation marks in js...
I have an input field using this js-function
function validate(xyz) {
"+umum+" == "yeah_it_is_ok";
if(xyz == ""+umum+"") {
alert("Hoera!");
return true;
} else {
alert("Too bad!");
return false;
}
}
What do I have to insert in the input-field to get the Hoera message?$
In other words, what is the function of a " or a + in js?
You don't have a syntax error in the function declaration,
but it will fail at execution time, because umum is not defined;
and surely you have a semantic error, because the only way to get "Hoera"
is to declare the umum var first and call the validate function later:
var umum;
validate("test value");
Of course, it always give a "too bad!" message unless you pass ""+undefined+""
as parameter. I think the right function should be:
function validate(xyz) {
var umum = "yeah_it_is_ok"; // or whatever you want to validate with..
if(xyz == umum) {
alert("Hoera!");
return true;
} else {
alert("Too bad!");
return false;
}
}
In this case, when calling validate("yeah_it_is_ok") you'll get an "Hoera!".
You would want to declare a variable like this:
var umum = "yeah_it_is_ok";
Note the var keyword and the use of a single equals for assignment.
Also, a pair of " characters is used to enclose a string variable, and the + will concatenate two strings. However, if you wish to have a double-quotation within a string you need to escape it with a backspace \. For example:
if(xyz == "\"+umum+\"") {
Single- and double-quote characters are used to delimit string constants. The + character is an operator that serves several purposes, including string concatenation, numeric addition, and asserting numeric "positiveness" (used often for its implicit side effects).
I think you mean to write your function like this.
function validate(xyz) {
umum = "yeah_it_is_ok";
if(xyz == umum) {
alert("Hoera!");
return true;
} else {
alert("Too bad!");
return false;
}
}
So then to answer your question, you can put the string that your looking for into the input-field. Which, since you don't have an input field in your example, we can just call the function with the correct string.
validate("yeah_it_is_ok");
Also it seems like you were thinking that you can use " or + in a variable. You can't do that. As others have suggested, you should learn the basics of JavaScript. w3schools.com and the Mozilla Developer Network are good places to do that.
http://www.w3schools.com/js/default.asp
https://developer.mozilla.org/en-US/learn/javascript
I believe you put a \ infront of it
so like
if(xyz == "\"+umum+\"") {

Allow only numeric input in a text input, and allow a hyphen as an optional first character

I need to automatically clean user entry into a text input - to only allow numbers, except for the first character, which could be a number or a hyphen.
So, for example, if the user types 138a29 it would be automatically updated to 13829.
I was using an onKeyPress event to check the keyCode to allow only numbers, but that's proved to be a little difficult to truly allow only numbers without breaking arrow keys, backspace keys, etc in some browsers. And now there is a new requirement to allow a hyphen(-) as an optional first character, but a hyphen is not valid anywhere else in the string.
I have the Prototype library to use for my particular project, but no jQuery.
The simplest way to do this is to avoid the keyCode and use the textbox's value on keyup. Something like this...
Event.observe('myInput', 'keyup', function(){
var value = this.value, first;
if(value.length == 0)
return;
first = value.charAt(0);
value = value.replace(/[^0-9]/g,'');
if(first == '-')
value = first + value;
this.value = value;
return true;
});
Try this
<script type="text/javascript">
function whatKey(e) {
var thetext = document.getElementById('tt'); // Current value
var theKey = String.fromCharCode(e.keyCode); // key entered
var combval = thetext.value + theKey; // Result would be this
return (!isNaN(combval) || combval=='-'); // if result OK, accept key
}
</script>

Categories

Resources