Can anyone send javascript code to validate the network mac address (eg. 02:41:6d:22:12:f1) It accepts value from 00:00:00:00:00:00 to ff:ff:ff:ff:ff:ff. On keypress event of textbox, I need to allow characters 0-9, a-f and : (colon). What I have so far is
macPattern = /^([0-9a-fA-F]{2}[:-]){5}[0-9a-fA-F]{2}$/i;
With this I am able throw exception for ff:ff:ff:ff:ff:ff but I also need to throw an exception for 00:00:00:00:00:00. My pattern is not throwing an exception.
Could you please give me a pattern through which I should able to throw an exception for both ff:ff:ff:ff:ff:ff and 00:00:00:00:00:00.
var MACAddress = document.getElementById("MACAddress");
var MACRegex=new RegExp("^([0-9a-fA-F][0-9a-fA-F]:){5}([0-9a-fA-F][0-9a-fA-F])$");
MACRegex.test(MACAddress);
var re = /^(?!(?:ff:ff:ff:ff:ff:ff|00:00:00:00:00:00))(?:[\da-f]{2}:){5}[\da-f]{2}$/i;
// ^------------blacklist------------^ ^----------pattern---------^
re.test('ff:ff:ff:ff:ff:ff'); // false
re.test('ff:ff:ff:ff:ff:fe'); // true
re.test('00:00:00:00:00:00'); // false
re.test('00:00:00:00:00:01'); // true
// and of course
re.test('00:00:00:00:01'); // false
re.test('00:00:00:00:00:0g') // false
Oh if we are answering about validating mac, here is mine: but this still doesn't answer the question: how to prevent characters that don't make up a mac address.
function isValidMac(mac) {
var a = mac.split(':');
if (a.length !== 6) {
return false;
}
for (var i=0; i<6; i++) {
var s = "0x"+a[i];
if (s>>0 === 0 || s.length != 4) {
return false;
}
}
return true;
}
I think that while the other answers are all valid, they missed the keypress aspect of the OP's question.
While that might not be important in this instance, I believe that the UX can be improved.
I would suggest;
-validating length =12
-accepting {0-9,a-f,A-F},
-alert {g-z,G-Z) (invalid character)
-ignore all others (including Tab, cr, lf, crlf)
-confirm exit after the 12th character
-display 3 forms; raw, couplet, quad
I have not yet had a chance to code but will submit and amend on completion
My answer is:
^([0-9a-fA-F]{2}[:-]){5}[0-9a-fA-F][1-9a-eA-E]$
Related
Answer #Wiktor Stribiżew suggested:
function myValidate(word) {
return (word.length === 1 || /[^A-Z]/i.test(word)) ? true : false;
}
Hello during the creation of an array I have a function that will not allow words with certain characters etc to be added to the array
function myValidate(word) {
// No one letter words
if (word.length === 1) {
return true;
}
if (word.indexOf('^') > -1 || word.indexOf('$') > -1) {
return true;
}
return false;
}
It seems like not the proper way of going about this and ive been looking into a regex that would handle it but have not been successful implementing it, tried numerous efforts like:
if (word.match('/[^A-Za-z]+/g') ) {
return true;
}
can some one shed some light on the proper way of handling this?
I suggest using a simpler solution:
function myValidate(word) {
return (word.length === 1 || /[^A-Z]/i.test(word)) ? false : true;
}
var words = ["Fat", "Gnat", "x3-2741996", "1996", "user[50]", "definitions(edit)", "synopsis)"];
document.body.innerHTML = JSON.stringify(words.filter(x => myValidate(x)));
Where:
word.length === 1 checks for the string length
/[^A-Z]/i.test(word) checks if there is a non-ASCII-letter symbol in the string
If any of the above condition is met, the word is taken out of the array. The rest remains.
EDIT: using test instead of match
You want to use test() because it returns a bool telling you if you match the regex or not. The match(), instead, always returns the matched elements. Those may be cast to true by coercion. This is not what you want.
To sum it all up you can just use this one-liner (no if needed and no quotes either, cannot get any simpler):
return word.test(/^[a-zA-Z][a-zA-Z]+$/); // two letter words
You should whitelist characters instead of blacklisting. That's one of the principles in security. In your case, don't tell what is wrong, but tell what is right:
if (word.test('/^[a-zA-Z]+$/')) { // two letter words
return false;
}
This will return false for all words that contain ONLY [a-zA-Z] characters. I guess this is what you want.
Your regex, instead, looked for illegal characters by negating the character group with the leading ^.
Two recommendations:
Just use regex in a positive way (without negation) and it'll be a lot easier to understand.
Also, validation functions normally return true for good data and false for bad data.
It is more readable this way:
if (validate(data))
{
// that's some good data we have here!
}
I've been doing a lot of searching, chopping and changing, but I'm...slightly lost, especially with regards to many of the regex examples I've been seeing.
This is what I want to do:
I have a text input field, size 32.
I want users to enter their telephone numbers in it, but I want them to enter a minimum of 10 numbers, separated by a single comma. Example:
E.g. 1
0123456789,0123456789 = right (first group is >=10 numbers, second group = >=10 numbers & groups are separated by a single comma, no spaces or other symbols)
E.g. 2
0123456789,,0123456789 = wrong (because there are 2 commas)
E.g. 3
0123456789,0123456789,0123456789 = right (same concept as E.g. 1, but with 3 groups)
I've got the following, but it does not limit the comma to 1 per 10 numbers, and it does not impose a minimum character count on the number group.
$(document).ready(function(){
$("#lastname").keypress(function (e) {
//if the letter is not digit then display error and don't type anything
if (e.which != 8 && e.which != 0 && String.fromCharCode(e.which) != ','
&& (e.which < 48 || e.which > 57)) {
//display error message
$("#errmsg").html("Digits Only").show().fadeOut("slow");
return false;
}
});
});
Preferably, I'd like to warn the user of where they are going wrong as well. For example, if they try to enter two commas, I'd like to specifically point that out in the error, or if they havent inserted enough numbers, i'd like to specifically point that out in the error. I'd also like to point out in the error when neither a number or a comma is inserted. I'd like to ensure that the tab, and F5 keys are not disabled on the keyboard as well. And very importantly, I'd like to specifically detect when the plus or addition key is used, and give a different error there. I think I'm asking for something a little complex and uninviting so sorry :/
The example code I provided above works pretty well across all browsers, but it doesn't have any of the minimum or maximum limits on anything I've alluded to above.
Any help would be appreciated.
As far as a regex that will check that the input is valid (1-3 phone numbers of exactly 10 digits, separated by single commas), you can do this:
^\d{10}(,\d{10}){0,2}$
Try like the below snippet without Regex
var errrorMessage = '';
function validateLength (no) {
if(!no.length == 10) {
return false;
}
return true;
}
function validatePhoneNumbers (currentString, splitBy) {
if(currentString) {
var isValid = true,
currentList = currentString.split(splitBy);
// If there is only one email / some other separated strings, Trim and Return.
if(currentList.length == 1) {
errrorMessage = 'Invalid Length in Item: 1';
if(validateLength( currentString.trim() )) isValid = false;
}
else if(currentList.length > 1) {
// Iterating mainly to trim and validate.
for (var i = 0; i < currentList.length; i++) {
var listItem = currentList[i].trim();
if( validateLength(listItem ) ) {
isValid = false;
errrorMessage = 'Invalid Length in Item:' + i
break;
}
// else if for some other validation.
}
}
}
return isValid;
}
validatePhoneNumbers( $("#lastname").val() );
Thanks for your help with my earlier question:
How to find all instances and display in alert
Now I discover that I need to include some invalid character validation.
I'm trying to figure out how to include a set of regex invalid characters as part of the validation that will also show up in the same alert/textbox/whatever as the "too long/too short" validation.
So, I have a textbox which users will type or paste comma separated values such as AAAAAAA,BBBBBBB,CCCCCCCC,DDDDDDDD
And they cannot be more or less than seven characters long and they can only include certain characters.
I currently have have two separate pieces of Javascript that I'm trying to now combine:
var Invalidchars = "1234567890!##$%^&*()+=[]\\\';./{}|\":<>?";
for (var i = 0; i < document.getElementById("TextBox1").value.length; i++) {
if (Invalidchars.indexOf(document.getElementById("TextBox").value.charAt(i)) != -1){
alert
and this
var val = document.getElementById("Textbox1").value,
err = $.grep(val.split(','), function(a) { return a.length != 7; });
if (err.length) {
alert("All entries must be seven (7) characters in length. Please correct the following entries: \n" + err);
return false;
}
return true;
Any help is much appreciated!
=================================================
SOLUTION
Took a while, but using Tenub's code (which didn't quite combine my two sets code, but was close enough), I finally figured out how to merge my two sets of code into one. Here's the code if anyone is ever interested in using it:
var val = document.getElementById("TextBox1").value,
err = $.grep(val.split(','), function(a) {return (a.length = (!/^[^0-9!##$%^&*()+=;.\/\{}|:<>\\?\[\]\'\"]{7}$/.test(a)));});
if (err.length){
document.getElementById("DIV1").style.display = "inline-block";
document.getElementById("TextBox2").value = err.join(',');
return callback (false);
}
document.getElementById("DIV1").style.display = "none";
return true;
The answer is as simple as it is elegant:
var val = document.getElementById("Textbox1").value;
if(!/[^0-9!##$%^&*()+=;./{}|:<>?\[\]\\\'\"]{7}/.test(val)) {
// handle invalid value
}
This tests that the string is 7 characters in length and does not contain any character within the brackets after the "^" (also some characters are escaped with a "\").
You can test in console:
/[^0-9!##$%^&*()+=;./{}|:<>?\[\]\\\'\"]{7}/.test('adfFDKZ'); // returns true
/[^0-9!##$%^&*()+=;./{}|:<>?\[\]\\\'\"]{7}/.test('adf(DKZ'); // returns false
Try this:
/*
* This regex matches all the invalid characters. I escaped the
* special characters.
*/
var regex = /.*[0-9!##\$%\^&\*\(\)\+=\[\]\\';\./\{\}\|":\<\>\?]+.*/;
var text = document.getElementById("TextBox1").value;
/* Test for match...much faster than a for-loop under any circumstances */
if (text.matches(regex)) {
alert("Invalid characters present. Please correct the input");
return false;
}
/* split on delimiter */
var err = $.grep(val.split(','), function(a) { return a.length != 7; });
if (err.length) {
alert("All entries must be seven (7) characters in length. Please correct the following entries: \n" + err);
return false;
}
Please tell me if there are any bugs in this. Also, the only real way to test for this in one step is to set up an enormously long regex. Also, with only one check, it would make it a little harder to guide the user to make the right correction. I will mention that.
I'm trying to validate a field with multiple conditions. I've got validation working with a single condition, but I'm not sure how to go about adding in addl conditions. Here's what I have so far:
priceEstimate: {
required: function() {
return $('#jobType').val() != '8';
}
}
I also need to make sure that the value of #jobType does not equal '9' or '10' either. I tried using an or operator, and that didn't seem to do the trick.
Any help would be greatly appreciated.
priceEstimate: {
required: function() {
var jobType = $('#jobType').val();
if (jobType < '8' && jobType > 10)
{
return true;
}else{
return false;
}
}
}
There are likely simpler ways to write it... but that will do ya. http://www.w3schools.com/js/js_comparisons.asp
In response to Jeremy's comment:
priceEstimate: {
required: function ()
{
var jobType = Number($('#jobType').val());
var _return = true;
switch (true)
{
case (jobType <= 1):
case (jobType >= 8 && jobType <= 10):
_return = false;
break;
}
return _return;
}
}
Ok, what we did here is a cascading switch. The expression is set to true, so it will run each case... we're then putting our logic in each individual case.
We know we don't want 1 or 0, so I have just have it set to false if it is equal to 1 or below, without a break in that case, it will simply run on to the next case and validate even further, so you'll want to try and keep the cases in order least -> greatest if nothing for the sake of your own sanity, lol.
Also I'm using Number() to flesh out the numeric value in the input, just in case, this way we also don't have to encapsulate all of our checks with quotes ('10') and they're treated like actual numbers and not just representations that may be translated into something that would fail the logic your striving for.
I have a form where a user inserts the GPS coordinates of a location to a corresponding photo. Its easy enough to filter out invalid numbers, since I just have to test for a range of (-90, 90), (-180, 180) for lat/long coordinates.
However, this also means that regular text is valid input.
I've tried changing the test pattern to
var pattern= "^[a-zA-Z]"
and is used in the function to detect alphabetical characters
$(".lat").keyup(function(){
var thisID= this.id;
var num = thisID.substring(3, thisID.length);
var thisVal = $(this).val();
//if invalid input, show error message and hide save button
if (pattern.test(thisVal)){
$("#latError"+num).fadeIn(250);
$("#save"+num).fadeOut(100)
}
else { //otherwise, hide error message and show save
$("#save"+num).fadeIn(250);
$("#latError"+num).fadeOut(100);
}
});
However, this doesn't work as Firebug complains that pattern.test is not a function What would solve this issue?
This is what i use in my project:
const regexLat = /^(-?[1-8]?\d(?:\.\d{1,18})?|90(?:\.0{1,18})?)$/;
const regexLon = /^(-?(?:1[0-7]|[1-9])?\d(?:\.\d{1,18})?|180(?:\.0{1,18})?)$/;
function check_lat_lon(lat, lon) {
let validLat = regexLat.test(lat);
let validLon = regexLon.test(lon);
return validLat && validLon;
}
check_lat_lon(-34.11242, -58.11547) Will return TRUE if valid, else FALSE
I hope this will be usefull to you!
Do you need to use regex? Consider the following:
var val = parseFloat(lat);
if (!isNaN(val) && val <= 90 && val >= -90)
return true;
else
return false;
How about the pattern -?[0-9]{1,3}[.][0-9]+ then you parseInt and check the range as you said before.
test() is a method of the RegExp object - you're running it on a string, so will fail.
Enclose your pattern in a RegExp literal (/pattern/), so
var pattern= /^[a-zA-Z]/
That will get rid of the errors you're getting, but you have a separate issue with regards to a) whether your pattern is correct for what you want it to do; b) whether you need REGEX at all.
REGEX acts on strings - it cannot be used to determine whether a number is within a given range (unless that range is 0-10 inclusive).
#flem's answer shows the best way to approach what you're doing - no REGEX needed. The call to parseInt() will catch non-numeric characters since it will return NaN if the value contains any.
#paul flemming gave a great answer, this answer extends his and includes longitude and uses typescript.
I would suggest this in place of regex for speed and simplicity.
Since, parseFloat takes a string and returns a number isNaN check isn't needed. This function allows a string or a number and converts it to string for parseFloat and will then do the simple threshold tests against +-90 & +-180.
function isValidLatAndLong(lat: number |string, lon:number|string){
const num1 = "" +lat; //convert toString
const num2 = "" +lon;
if (parseFloat(num1) <= 90 && parseFloat(num1) >= -90 && parseFloat(num2) <= 180 && parseFloat(num2) >= -180){
return true;
}
else{
return false;
}
}