javascript validation to check # at start of user input: not email validation - javascript

I have to check whether a form field contains '#' at start of user input & is it contains it at all. It works fine for checking if its at start of the string. But when I add checking whether input contains '#' at all or not. It fails. Here is my code
function email_valid(field)
{
var apos=field.update.value;
apos=apos.indexOf('#');
if (apos>0 ||((apos.contains('#')== 'FALSE')))
{ alert('plz enter valid input');
return false;
}
else
{ return true; }
}
EDIT
This function in this form is checking both if # is at 1st place & 2ndly is it in the input at all or not.
function #_valid(field)
{
var ref=field.update.value;// I needed ref 4 other things
var apos=ref.indexOf('#');
if (apos>=0 )
{
if (apos==0)
{
return true;
}
else { field.t_update3.value="";
alert('plz enter a valid refernce');
return false;
}
}
else { field.t_update3.value="";
alert('plz enter a valid refernce');
return false;
} }

Consider:
var apos = value.indexOf('#');
if (apos >= 0) {
// was found in string, somewhere
if (apos == 0) {
// was at start
} else {
// was elsewhere
}
} else {
// not in string
}
and
var apos = value.indexOf('#');
if (apos == 0) {
// was at start
} else if (apos > 0) {
// was elsewhere
} else {
// not in string
}

Why not just
if (apos !== 0) { /* error; */ }
The "apos" value will be the numeric value zero when your input is (as I understand it) valid, and either -1 or greater than 0 when invalid.
This seems like a strange thing to make a user of your site do, but whatever. (If it's not there at all, and it must be there to be valid, why can't you just add the "#" for the user?)

You can just check to make sure that apos is greater than -1. Javascript's indexOf() will return the current index of the character you're looking for and -1 if it's not in the string.
edit Misread a bit. Also make sure that it's not equal to 0, so that it's not at the beginning of the string.

function email_valid(field)
{
var fieldValue =field.update.value;
var apos = apos.indexOf('#');
if (apos > 0 || apos < 0)//could also use apos !== 0
{ alert('plz enter valid input');
return false;
}
else
{ return true; }
}
apos is the value returned by indexOf, it will be -1 if there is no # in the user input. It will be 0 if it is the first character. It will be greater than 0 if the user input contains an # . JavaScript has no contains method on a String.

Try:
function email_valid(field) {
//var apos=field.update.value;
var apos = field;
//apos=apos.indexOf('#');
apos = apos.indexOf('#');
if( (apos < 0) ) {
//alert('plz enter valid input');
alert('false');
} else {
alert('true');
}
}
email_valid('blah');
Checks for # anywhere. Or, if you want to check for # just at the beginning, change if( (apos < 0) ) { to if( (apos == 0) ) {. Or, if you want to make sure it's not at the beginning, then if( (apos > 0) ) {.

apos will be -1 if the string was not found. So your code should be as follows:
function email_valid(field)
{
var apos=field.value;
apos=apos.indexOf('#');
if (apos<=0) // handles '#' at the beginning and not in string at all.
{
alert('plz enter valid input');
return false;
}
else
{ return true; }
}
I also changed your initial assignment to remove the .update portion as that would cause it to fail when field is a reference to an input.

In the second if condition, apos is a number, not a string.
You're trying to write
if (field.update.value.charAt(0) == '#' && field.update.value.indexOf('#', 1) < 0)

Learn about Regular expressions if you haven't already. Then lookup Javascript's String#match. There is no need to find wether the input starts with an "#" as if it contains an "#" that will also return true if the "#" is at the start of the string.
Also, for free, return true and return false are generally bad style. Just return the thing you passed to if (that evaluates to a boolean).
All in all:
function validate_input(str) {
return str.match(/#/);
}
I reccomend passing the function a string (field.value or some-such) rather than the field itself as it makes it more generic.

Update: revised answer based on comments. code below will only return true if the value contains an "#" symbol at the first character.
If this is a JavaScript question, then this should be fine.
function email_valid(field){
var apos=field.update.value;
if(apos.indexOf('#') != 0){
alert('plz enter valid input');
return false;
} else {
//field contains an '#' at the first position (index zero)
return true;
}
}
That said, your parameter "field" if it actually refers to an input field element, should only require this code to get the value (e.g. I'm not sure where the ".update" bit comes into play)
var apos = field.value;
I would also rename this function if it isn't doing "email validation" to something a little more appropriately named.

Related

Password characters checker in JavaScript

I'm trying to build something that checks the password that I enter in a prompt has a upper case letter , one lower case , one special symbol and a length...but sometimes when I am entering just upper case cand lower case letters I get no alert ( you will see it in the code )..
Also I have the following error in the console : Cannot read property 'length' of null at hasUpperCase"
I will post the code here:
var parola = prompt('Introdu parola:');
function hasUpperCase(parola){
for(i = 0; i < parola.length; i++){
if(parola[i] === parola[i].toUpperCase()){
return true;
}
}
}
function hasLowerCase(parola){
for(i = 0; i < parola.length; i++){
if(parola[i] === parola[i].toLowerCase()){
return true;
}
}
}
var minLength = 8;
function isLongEnough(parola){
if(parola.length >= minLength){
return true;
}
}
function hasSpecialCharacter(parola){
var specialCharacters = "£$%^&*#~";
for(i = 0; i < parola.length; i++){
for(j = 0; j < specialCharacters.length; j++){
if(parola[i] === specialCharacters[j]){
return true;
}
}
}
}
function isPasswordValid(parola){
if(!hasUpperCase(parola)){
alert('The password requires a capital letter!');
var parola = prompt('Introdu parola:');
}
if(!hasLowerCase(parola)){
alert('The password requires a lower case letter!');
var parola = prompt('Introdu parola:');
}
if(!isLongEnough(parola)){
alert('The password is not long enough!');
var parola = prompt('Introdu parola:');
}
if(!hasSpecialCharacter(parola)){
alert('The password requires a special character');
var parola = prompt('Introdu parola:');
}
if((hasSpecialCharacter(parola) && hasLowerCase(parola) && hasUpperCase(parola) && isLongEnough(parola)){
}
}
isPasswordValid(parola);
Aside from implementation concerns, first fix the error by checking for null or undefined first thing in your isPasswordValid function. Also, as wisely suggested by Patrick, use regex for these checks. I'd also recommend always returning a bool in your check functions by returning false after each for loop.
You could use the the regex
/^(?=.{1,}[a-z])(?=.{1,}[A-Z])(?=.{1,}([£$%^&*#~])).{8,20}$/
to match all of those examples.
Here's a brief explanation:
^ // the start of the string
(?=.{1,}[a-z]) // use positive look ahead to see if at least one lower case letter exists
(?=.{1,}[A-Z]) // use positive look ahead to see if at least one upper case letter exists
(?=.{1,}[£$%^&*#~]) // use positive look ahead to see if at least one underscore or special character exists
.{8,20} // gobble up the entire string and match between 8 and 20
$ // the end of the string
You would use it like this:
function isPasswordValid(parola)
{
if(!parola)
return false;
var reg = /^(?=.{1,}[a-z])(?=.{1,}[A-Z])(?=.{1,}([£$%^&*#~])).{8,20}$/g;
if(parola && reg.test(parola)){
//do stuff here
}
}
if you don't want to do all of that, for your code its a very simple fix!
remove the extra ( and add this to your test:
function isPasswordValid(parola){
if(!parola)
return false;
.
.
.
.
.
.
if(parola && (hasSpecialCharacter(parola) && hasLowerCase(parola) && hasUpperCase(parola) && isLongEnough(parola))){
// do stuff here
}
checking just the varriable will evaluate as false if it is:
null
undefined
NaN
empty string ("")
0
false
and as true otherwise.
This should fix all of your issues.
UPDATE
Thank you Patrick Roberts for pointing out the error in the regex. below is a working example.
const regex = /^(?=.{1,}[a-z])(?=.{1,}[A-Z])(?=.{1,}([£$%^&*#~])).{8,20}$/g;
const str = 'aA$';
let m;
if ((m = regex.exec(str)) !== null) {
// The result can be accessed through the `m`-variable.
m.forEach((match, groupIndex) => {
console.log(`Found match, group ${groupIndex}: ${match}`);
});
}
else{
console.log('no match found')
}
To address the error you mentioned, namely
Cannot read property 'length' of null at hasUpperCase
You must check that the value returned from prompt() is not null as a result of the input being cancelled by the user.
Otherwise, you can read the string from an <input> to ensure that the value is always a string.
Some other issues are that you don't take advantage of the simplicity of regular expressions to enforce some of the constraints you implement with for loops, which would make your code a lot more readable, maintainable, and easier to digest.
Also as I suggested in the comments, it's better practice to allow isLongEnough() to accept a parameter, a local variable, or even the minlength attribute on the password to indicate the minimum length, rather than a scoped variable as is currently being used.
Finally, it would help to take advantage of the pattern attribute of the <input> element to automate some of the requirements that can be expressed in a regular expression. Note, I tried to include this in the solution below, but the look-aheads in pattern="(?=[a-z])(?=[A-Z])(?=[£$%^&*#~])" seemed to behave kind of buggy, so I've omitted this particular suggestion.
Working these suggestions into a solution might look something like this:
function hasUpperCase(parola) {
return /[A-Z]/.test(parola);
}
function hasLowerCase(parola) {
return /[a-z]/.test(parola);
}
function isLongEnough(parola, minLength) {
return parola.length >= minLength;
}
function hasSpecialCharacter(parola) {
return /[£$%^&*#~]/.test(parola);
}
function checkPasswordValidity() {
var parola = this.value;
var minLength = Number(this.getAttribute('minlength'));
var errors = [];
if (!isLongEnough(parola, minLength)) {
errors.push('a minimum length of ' + minLength + ' characters');
}
if (!hasUpperCase(parola)) {
errors.push('a capital letter');
}
if (!hasLowerCase(parola)) {
errors.push('a lower case letter');
}
if (!hasSpecialCharacter(parola)) {
errors.push('a special character');
}
if (errors.length > 0) {
this.setCustomValidity('The password requires ' + errors.join(', '));
} else {
this.setCustomValidity('');
}
}
document.querySelector('[name="password"]').addEventListener('input', checkPasswordValidity);
<form>
<input name="password" type="text" placeholder="Introdu parola" minlength="8" required>
<input type="submit" value="Submit">
</form>
That error was cause of the prompt cancellation. So, i think you should be using the value in the text field and validate that
Here is the working way for doing that
$('#form').on('submit', function() {
event.preventDefault();
var parola = $('#txt_name').val();
isPasswordValid(parola);
})
function hasUpperCase(parola){
for(i = 0; i < parola.length; i++){
if(parola[i] === parola[i].toUpperCase()){
return true;
}
}
}
function hasLowerCase(parola){
for(i = 0; i < parola.length; i++){
if(parola[i] === parola[i].toLowerCase()){
return true;
}
}
}
var minLength = 8;
function isLongEnough(parola){
if(parola.length >= minLength){
return true;
}
}
function hasSpecialCharacter(parola){
var specialCharacters = "£$%^&*#~";
for(i = 0; i < parola.length; i++){
for(j = 0; j < specialCharacters.length; j++){
if(parola[i] === specialCharacters[j]){
return true;
}
}
}
}
function isPasswordValid(parola){
if(!hasUpperCase(parola)){
alert('The password requires a capital letter!');
return;
}
if(!hasLowerCase(parola)){
alert('The password requires a lower case letter!');
return;
}
if(!isLongEnough(parola)){
alert('The password is not long enough!');
return;
}
if(!hasSpecialCharacter(parola)){
alert('The password requires a special character');
return;
}
if(hasSpecialCharacter(parola) && hasLowerCase(parola) && hasUpperCase(parola) && isLongEnough(parola)){
alert('yayyy!!');
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form">
<input type="text" name="text" value="" id="txt_name">
<input type="submit" value="Check password">
</form>
isPasswordValid calls your 4 functions in sequence to check their validity, but does not re-check the prompt's value if any of them fail. It just asks you to enter something else and then continues on. You can re-check the prompt's validity by re-calling isPasswordValid at the end of the function. Calling it at the end of the function prevents additional prompts from appearing when you enter invalid inputs and then a valid one.
Note: calling toLowerCase() on a symbol returns that symbol, so ####AAAA would have been valid. To get around this I used regular expressions in your functions.
var parola = prompt('Introdu parola:');
function hasUpperCase(parola) {
return /[A-Z]/.test(parola)
}
function hasLowerCase(parola) {
return /[a-z]/.test(parola);
}
var minLength = 8;
function isLongEnough(parola) {
return parola.length >= minLength;
}
function hasSpecialCharacter(parola) {
return /[£$%^&*#~]/.test(parola);
}
var errorMessage;
function isPasswordValid(parola) {
if (!hasUpperCase(parola)) {
errorMessage = 'The password requires a capital letter!';
}
else if (!hasLowerCase(parola)) {
errorMessage = 'The password requires a lower case letter!';
}
else if (!isLongEnough(parola)) {
errorMessage = 'The password is not long enough!';
}
else if (!hasSpecialCharacter(parola)) {
errorMessage = 'The password requires a special character';
}
else {
alert('Password is valid');
return;
}
parola = prompt(errorMessage);
isPasswordValid(parola);
}
isPasswordValid(parola);

Check if key is in array-JavaScript

I have this JavaScript code
function checkTextField() {
var textVal = document.getElementById("textfield").value;
if (textVal == '', textfield.value.length <= 31)
{
alert('Wrong Key-Code. Key-Code must have 32 characters!');
}
else //Its all about how to decrypt a database file called ,,Salam Horia Allah,,!(good luck hackers)
{
{
var text = document.getElementById("textfield").value;
if (text ==
"3e6898f92134d05408dfed30b268d9d6",
"fa0f82cc02a6cdc35072ee5ce2b0c379",
"6a1df566fcaabca717aa1b81c3e0bd31",
"dc0beea186c5f5c2110bedbeccc5a7aa",
"1a317dbc4587268809b67179c391a5da9debb6261e3a3bcf7e6cd2b34356fc40",
"08a8c9750b3d184e6450b98fa90208bbd6c07171c0cce929bc52be1fdb44b09c",
"ac8ce3072f41269be4626539650bb1981c2939db0ffd576f240d06b0b7470c11",
"23a306626c5e9f83d8ce6012f9209fb8f3adcc1a098ffbfafd3c7965ed2c30a6",
"teBy%udu#uMuGyZe4uTyHeNa5yLy6avyTumypy8uHaGujytaWy",
"SezyDuXaquneguzuLatydy7e2ygu4y5e7uqe3e6uheVuVeSumu"
)
{
location.href = "http://79.115.70.31:8521/InWork/"
}
else {
alert("Wrong Key")
}
}
}
}
and here is what happen:
i have a textbox and a button,when i insert a key from if (text ==
"3e6898f92134d05408dfed30b268d9d6",
"fa0f82cc02a6cdc35072ee5ce2b0c379",
"6a1df566fcaabca717aa1b81c3e0bd31",
"dc0beea186c5f5c2110bedbeccc5a7aa",
And when someone press that button, I want that script to check if one of that keys are in text field, if is true the request will send to another page, if is not true, show an alert.
But my problem is, whatever I write in that textbox it send me to that page, also I got an alert if textbox have <31 characters.
The comma operator works inside of an if clause, but it takes the last value, not a logical OR, which is here required.
(An input returns always a string and if empty, the string length is zero. A check for emptiness and a check for a length which is smaller than a value is superfluous, because the length check includes a zero length as well.)
if (textVal == '' || textfield.value.length <= 31)
// ^^
Beside that, I suggest to use an array for the valid keys for checking and check only if the value is in the array, then proceed or give an alert.
Another point is to assign the value of the input only once and use it in the whole function with the variable. Do not use a mixed style with a variable and document.getElementById("textfield").value together.
function checkTextField() {
var keys = ["3e6898f92134d05408dfed30b268d9d6", "fa0f82cc02a6cdc35072ee5ce2b0c379", "6a1df566fcaabca717aa1b81c3e0bd31", "dc0beea186c5f5c2110bedbeccc5a7aa", "1a317dbc4587268809b67179c391a5da9debb6261e3a3bcf7e6cd2b34356fc40", "08a8c9750b3d184e6450b98fa90208bbd6c07171c0cce929bc52be1fdb44b09c", "ac8ce3072f41269be4626539650bb1981c2939db0ffd576f240d06b0b7470c11", "23a306626c5e9f83d8ce6012f9209fb8f3adcc1a098ffbfafd3c7965ed2c30a6", "teBy%udu#uMuGyZe4uTyHeNa5yLy6avyTumypy8uHaGujytaWy", "SezyDuXaquneguzuLatydy7e2ygu4y5e7uqe3e6uheVuVeSumu"],
text = document.getElementById("textfield").value;
if (keys.indexOf(text) !== -1) {
location.href = "http://79.115.70.31:8521/InWork/";
} else {
alert("Wrong Key");
}
}
Well you need to compare you tex with each key available so
function checkTextField() {
var textVal = document.getElementById("textfield").value;
var yourKeys =[ "3e6898f92134d05408dfed30b268d9d6",
"fa0f82cc02a6cdc35072ee5ce2b0c379",
"6a1df566fcaabca717aa1b81c3e0bd31",
"dc0beea186c5f5c2110bedbeccc5a7aa",
"1a317dbc4587268809b67179c391a5da9debb6261e3a3bcf7e6cd2b34356fc40",
"08a8c9750b3d184e6450b98fa90208bbd6c07171c0cce929bc52be1fdb44b09c",
"ac8ce3072f41269be4626539650bb1981c2939db0ffd576f240d06b0b7470c11",
"23a306626c5e9f83d8ce6012f9209fb8f3adcc1a098ffbfafd3c7965ed2c30a6",
"teBy%udu#uMuGyZe4uTyHeNa5yLy6avyTumypy8uHaGujytaWy",
"SezyDuXaquneguzuLatydy7e2ygu4y5e7uqe3e6uheVuVeSumu"];
if (textVal == '', textfield.value.length <= 31)
alert('Wrong Key-Code. Key-Code must have 32 characters!');
else {
var text = document.getElementById("textfield").value;
var i = yourKeys.length;
while(i--){
if(text == yourKeys[i] )
location.href = "http://79.115.70.31:8521/InWork/"
else
alert("Wrong Key")
}
}
}

Preventing the user from typing certain characters?

I need a field which can only take numbers, but not allow for signs such as "+", "-", "*" and "/". 0 can also not be the first number. If I make an Input field and set it's type to "number" I'm still allowed to write at least "+" and "-", and I can't quite seem to prevent the user from writing 0 as the first number either.
$('input#update-private-ext').on('keydown', function (e) {
var value = String.fromCharCode(e.keyCode);
if ($(this).text.length == 0 && value == 0) {
return false;
}
});
The above was my first attempt at making the function disallow 0 as the first character, but it doesn't seem to work. It just lets me write 0 as the first character. I also tried this to stop the signs from showing up:
$('input#update-private-ext').on('keydown', function (e) {
var badChars = '+-/*';
var value = String.fromCharCode(e.keyCode);
if ($(this).text.length == 0 && value == 0) {
return false;
}
if (badChars.indexOf(value) == -1) {
return false;
}
});
But with the badChars check, I cannot write anything in my field. So what am I missing here?
You should use e.key to get the current key pressed. String.fromCharCode(e.keyCode) gives the wrong result.
Also you should check if the bad chars is not -1. If it is, then your char is not a bad character and so you should not enter the if.
If you want to get the length of the input field you should use jQuery's .val() and not .text(). Or you can simply do it without jQuery using this.value.length.
$('input#update-private-ext').on('keydown', function (e) {
var badChars = '+-/*';
var value = e.key;
if (this.value.length == 0 && value == '0') {
return false;
}
if (badChars.indexOf(value) !== -1) {
return false;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="update-private-ext">
When you compare numbers and strings you must remember that numbers are encoded by using character codes from 48 to 57 and comparing strings with numbers is error-prone in JavaScript as there are many implicit coercions. You should be comparing objects of the same type to avoid the confusion.
In your case, the comparison should be done in the way that parsed string from the String.fromCharCode equals '0' - zero character (string), not the 0 as a number.
There are also issues of the keyCode parsing which yield strange values for the symbols because you would have to manually consider if Shift and other meta keys are pressed when parsing. Save yourself a trouble and just use e.key to get parsed key value.
By the way, please see the difference between this and $(this). Basically, in your case, it means that real instance of the input field is the first element of JQuery iterator - $(this)[0]. You may then just use this, which is automatically set to the target element in the event handler.
Please see the following example of blocking first 0 with debug information printed out:
$('input#update-private-ext').on('keydown', function (e) {
var value = e.key;
console.log('Typed character:');
console.log(value);
console.log('$(this)');
console.log($(this));
console.log('this (input element):');
console.log(this);
console.log("input's value:");
console.log(this.value);
if (this.value.length == 0 && value == '0') {
console.log('blocked');
return false;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="update-private-ext" />
In order to block other characters you can just filter them the following way (remember that indexOf returns -1 when the index is not found):
$('input#update-private-ext').on('keydown', function (e) {
var badChars = '+-/*';
var value = e.key;
if (this.value.length == 0 && value == '0') {
return false;
}
//Please note NOT EQUALS TO -1 which means not found.
if (badChars.indexOf(value) !== -1) {
return false;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="update-private-ext" />
You can do something like this below:
1. Check for bad chars if badChars.indexOf(v) >= 0.
2. Disallow starting from 0 by checking if the input starts from 0 and if yes, set the input field to blank.
This can give you a start!
$('input#update-private-ext').on('keydown', function(e) {
var badChars = '+-/*';
var v = e.key;
if (badChars.indexOf(v) >= 0) {
return false;
}
if ($(this).val().startsWith('0')) {
$(this).val("");
return false;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="update-private-ext" />

Numeric Fields on HTML elements

I have been trying to allow numeric field and one decimal point in my Grid.Its work fine when its suitable for input box.
when i am calling onKeyPress the script work fine for "input box" rather than on "Div element"
In "Div element",when i am supposed to use this .It allow to access only for number rather Alphabet
hence,while coming to "decimal place" its not working as it should.[ It's allowing many Dot's]
<script>
function getKey(e)
{
if (window.event)
return window.event.keyCode;
else if (e)
return e.which;
else
return null;
}
function restrictChars(e, obj)
{
var CHAR_AFTER_DP = 2; // number of decimal places
var validList = "0123456789."; // allowed characters in field
var key, keyChar;
key = getKey(e);
if (key == null) return true;
// control keys
// null, backspace, tab, carriage return, escape
if ( key==0 || key==8 || key==9 || key==13 || key==27 )
return true;
// get character
keyChar = String.fromCharCode(key);
// check valid characters
if (validList.indexOf(keyChar) != -1)
{
// check for existing decimal point
var dp = 0;
if( (dp = obj.value.indexOf( ".")) > -1)
{
if( keyChar == ".")
return false; // only one allowed
else
{
// room for more after decimal point?
if( obj.value.length - dp <= CHAR_AFTER_DP)
return true;
}
}
else return true;
}
// not a valid character
return false;
}
</script>
<div onKeyPress="return restrictChars(event, this)">
Any Ideas how we could achieve it
For an <input>, it is required to check the value attribute, hence why obj.value is used in your code above. A div element doesn't have a value attribute. You have to check it's innerHTML (mdn docs). If you replace all instances of obj.value with obj.innerHTML, your code should work.
You need to use jQuery keypress() method to handle this right:
$("#d input").keypress(function(event){
return restrictChars(event);
});
See the working fiddle:
http://fiddle.jshell.net/ePvJ8/1/

Required only one dot at the end of nameserver

The regex below works nice except I need only one dot (.) at the end for nameserver. For example if user submit ns1.hello.com there will be error. Accepted format is with dot at the end like this ns1.hello.com. Help me please. Thank you.
<script type="text/javascript">
function validSubdomain() {
var re = /^[a-zA-Z0-9][a-zA-Z0-9.-]+\.$/;
var val = document.getElementById("nameserver").value;
var val2 = document.getElementById("nameserver2").value;
if(val == '' && val2 == ''){
alert("Please fill in the name server");
document.forms['namaform'].elements['nameserver'].focus();
return false;
}
if(val == ''){
alert("Please fill in the name server 1");
document.forms['namaform'].elements['nameserver'].focus();
return false;
}
if(val2 == ''){
alert("Please fill in the name server 2");
document.forms['namaform'].elements['nameserver2'].focus();
return false;
}
var parts = val.split('.');
var parts2 = val2.split('.');
if (parts.length < 3)
{ alert('invalid nameserver format')
document.forms['namaform'].elements['nameserver'].focus();
return false;
}
else if (parts2.length < 3)
{ alert('invalid nameserver 2 format')
document.forms['namaform'].elements['nameserver2'].focus();
return false;
}
if( !re.test(val)) {
alert("invalid nameserver 1 format");
return false;
}
else if( !re.test(val2)) {
alert("invalid nameserver 2 format");
}
else{namaform.submit();}
}
</script>
Two things wrong with:
if(re.test(val && val2)) {
alert("valid format");
}
if(!re.test(val && val2)) {
alert("invalid format");
}
First of all, have you never heard of else? It's there specifically so you don't have to repeat a test in the negative.
Second, you are trying to && together the two string and then passing the resulting boolean to re.test(). Since a boolean converts to the string "true" or "false" it will never ever match.
Change to:
if( re.test(val) && re.test(val2)) {
alert("valid format");
}
else {
alert("invalid format");
}
Also note that your regex is wrong. It would accept a..b as input, which is clearly not valid. Try this instead:
var re = /^([a-z0-9-]+\.)+[a-z]{2,3}\.$/i;
This will broadly match most domains with unlimited number of subdomain levels, provided there's a . at the end.
EDIT to disallow - at the front of a section:
var re = /^([a-z0-9][a-z0-9-]*\.)+[a-z]{2,3}\.$/i;
It sounds like you're just saying that this:
var re = /^[a-zA-Z0-9][a-zA-Z0-9.-]+[a-zA-Z0-9]$/;
needs to be this:
var re = /^[a-zA-Z0-9][a-zA-Z0-9.-]+\.$/;
?
If you want to match a special character in a regex (also referred to as 'metacharacters') you need to escape it with a backslash. So, just before the $ in your regex, include
\.
to match the dot at the end of the string.

Categories