Javascript test() method syntax error? - javascript

I'm attempting to convert (what I've found to be) the best email validation function (located here: http://www.linuxjournal.com/article/9585?page=0,3) from php to javascript. Regardless of the fact that "you shouldn't validate with javascript because javascript can be disabled". Obviously I can't leave in the checkdnsrr() portion of the function, but everything else should be doable with javascript.
So far the function works as expected up until this line:else if(/\.\./.test(domain)) {
I know it's pretty useless without context, so the full function is below. What's also weird is that it gives a "pass" to a line with the exact same regex pattern:else if(/\.\./.test(local)) { which is used a few lines before it. Strange.
function validEmail(email) {
var isValid = true;
var atIndex = email.indexOf("#");
var ending = email.length - 1;
if(typeof(atIndex) == "boolean" && !atIndex) {
isValid = false;
}
else {
var domain = email.substr(atIndex+1);
var local = email.substr(0, atIndex);
var localLen = local.length;
var domainLen = domain.length;
if(localLen < 1 || localLen > 64) {
// local part length exceeded
isValid = false;
}
else if(domainLen < 1 || domainLen > 255) {
// domain part length exceeded
isValid = false;
}
else if(local[0] == '.' || local[localLen-1] == '.') {
// local part starts or ends with '.'
isValid = false;
}
else if(/\.\./.test(local)) {
// local part has two consecutive dots
isValid = false;
}
else if(/^[A-Za-z0-9\\-\\.]+$/.test(domain) == false)
// character not valid in domain part
isValid = false;
}
else if(/\.\./.test(domain)) {
// domain part has two consecutive dots
isValid = false;
}
else if(/^(\\\\.|[A-Za-z0-9!#%&`_=\/$'*+?^{}|~.-])+$/.test(local.replace("\\\\",""))) {
// character not valid in local part unless
// local part is quoted
if(/^"(\\\\"|[^"])+"$/.test(local.replace("\\\\",""))) {
isValid = false;
}
}
}
return isValid;
}

You missed a { in the previous if.
Therefore, that else has no if connected to it.

Related

exporting function return value

I have a code below
function createRoom(){
$(document).keyup(function(event) {
if ($("#room_name").is(":focus") && event.key == "Enter") {
var plainText = document.querySelector(".create-room-class").value;
var createRoomName = plainText.replace(/(<([^>]+)>)/gi, "");
createRoomName = createRoomName.replace(/ +/g, "");
createRoomName = createRoomName.trim();
if(createRoomName.length == 0){
alert("empty");
} else if(createRoomName.length < 5){
alert("Room name must be equal or longer than 5 characters");
} else if(!createRoomName.length == 0)
{
getCreatedRoomName(createRoomName);
window.location = createRoomName;
}
}
});
}
createRoom();
function getCreatedRoomName(x){
return x;
}
What it does is first checks if input field is not empty and if not smaller than 5 characters. If everything is fine then we pass that value to a function and then redirect to that created name url. Look below.
getCreatedRoomName(createRoomName);
window.location = createRoomName;
And we return value (return x)
function getCreatedRoomName(x){
return x;
}
How can I retrieve that returned value in nodejs? I tried modules it doesn't work for some reason.

Creating a pattern for a number which must be prefixed by 3 letters eg (IKA111111)

function validatetest(e)
{
debugger;
e.preventDefault();
// Declare all the variables here
var firstName = document.getElementById("firstName").value;
var lastName = document.getElementById("lastName").value;
var title = document.getElementById("title").value;
var healthNumber = document.getElementById("healthNumber").value);
var email = document.getElementById("email").value;
var telephoneNumber = parseInt(document.getElementById("telephoneNumber").value);
var validHealth = /^[A-Z]{3}[0-9]{6}$/;
var validText = /^[a-zA-Z]*$/;
var validLastText = /^[a-zA-Z-]*$/;
var validEmail = /^[a-zA-Z0-9._-]+#[a-zA-Z0-9._-]+\.[a-zA-Z]{2,6}$/;
//var n = healthNumber.startsWith("ZHA");
if(firstName!="" && lastName!= "" && title!="" && email !="")
{
if(email.match(validEmail))
{
if(!isNaN(telephoneNumber) && telephoneNumber >= 11111111111 && telephoneNumber <= 99999999999)
{
if(firstName.match(validText) && firstName.length >1)
{
if(lastName.match(validLastText) && lastName.length> 1)
{
if(healthNumber.match(validHealth))
{
alert("All information is Validated");
return true;
}
else
{
alert("error error");
return false;
}
}
else
{
document.getElementById("error4").innerHTML="letters and hypen only";
return false;
}
}
else
{
document.getElementById("error").innerHTML="letters only and more then one character";
return false;
}
}
else
{
document.getElementById("error2").innerHTML="Telephone number must be 11 num digits long";
}
}
else
{
document.getElementById("error3").innerHTML="email is not a valid format ";
return false;
}
}
else
{
alert("All fields must be entered except telephone Number ");
return false;
}
}
i am trying to create a validation process by using a pattern for a user inputted healthnumber so that it validates whether 3 letters are entered followed by 6 numbers via user input. (MIC123456 is example so MIC always has to been entered , those specific letters)
Not sure if my technique is correct by using a pattern stored in the ValidHeath variable as you can i have used this idea for my email validation etc .
You have an extra + in your regex, make it
var validHealth = /^[A-Z]{3}[0-9]{6}$/;
Demo
var isMatch = !!"IKA111111".match(/^[A-Z]{3}[0-9]{6}$/);
isMatch ? console.log( "Matching" ) : console.log( "Not Matching" );

Validation on textbox using jquery for pan Number format

I have to add Pan no in my website Application but i have to use jquery for validation so that first 5 no. should be alphabet then 4 no. should be numeric and the last Questions should be alphabet.
$('#txtPANNumber').keypress(function (event) {
var key = event.which;
var esc = (key == 127 || key == 8 || key == 0 || key == 46);
//alert(key);
//var nor = $("#txtPANNumber").mask("aaaaa9999a");
var regExp = /[a-zA-z]{5}\d{4}[a-zA-Z]{1}/;
var txtpan = $(this).val();
if (txtpan.length < 10 ) {
if( txtpan.match( regExp) ){
//event.preventDefault();
}
} else { event.preventDefault(); } });
Please provide some solutions
This will do
/[a-zA-z]{5}\d{4}[a-zA-Z]{1}/
Check here
Code
$('#txtPANNumber').change(function (event) {
var regExp = /[a-zA-z]{5}\d{4}[a-zA-Z]{1}/;
var txtpan = $(this).val();
if (txtpan.length == 10 ) {
if( txtpan.match(regExp) ){
alert('PAN match found');
}
else {
alert(Not a valid PAN number);
event.preventDefault();
}
}
else {
alert('Please enter 10 digits for a valid PAN number');
event.preventDefault();
}
});
You can use below regex to validate input for PAN.
[A-Z]{5}[0-9]{4}[A-Z]{1}
Function for JS :
function validatePAN(pan){
var regex = /[A-Z]{5}[0-9]{4}[A-Z]{1}$/;
return regex.test(pan);
}
But don't rely only on JS validation, as JS validation can easily disabled from client side. Put a check on server side as well for inputs.
Also you need to change your if condition to something like below :
if(length == 10)

Combining 2 IF/ELSE statements (validation)

I am trying to combine 2 IF/Else statements to create one validation function. This is my code for the 2 separate validations:
function validateCarsMin(v){
if (tfRateLoc1.getValue() > 0 || tfRateLoc2.getValue() > 0){
if (tfRateLoc3.getValue() > 0){
return '1B cannot contain a value if CW is entered';
}
} else return true
}
function validateRateLoc3(v){
if (v != ''){
if(tfRateLoc3.getValue() < tfRateLoc4.getValue()){
return true;
} else {
return 'This Value is not valid';
}}
}
I did not know if there was a best practice for this and it so, what would it be?
Thanks for the help on the last question I had.
Change the functions to return either true or false. You can push the msgs to an array to be used later.
var errorMsgs = [];
function validateCarsMin(){
if (tfRateLoc1.getValue() > 0 || tfRateLoc2.getValue() > 0){
if (tfRateLoc3.getValue() > 0){
errorMsgs.push('1B cannot contain a value if CW is entered');
return false;
}
} else{
return true;
}
}
function validateRateLoc3(){
if(tfRateLoc3.getValue() < tfRateLoc4.getValue()){
return true;
} else {
errorMsgs.push('This Value is not valid');
return false;
}};
}
function validateForm(){
var isValid = false;
isValid = validateCarsMin();
isValid = (!isValid) ? isValid:validateRateLoc3();
return isValid;
}
Note I removed the v parameter because it seemed irrelevant. It is not used in the first function and it creates a syntax error in the second.

How to turn ternary if statement back into standard javascript?

I'm working with this ternary if statement:
a[textProp] = _newText + ' (' + (_newText === a[textProp] ? 'no change' : 'changed') + ')';
And I'd like to turn it back into standard javascript (for the sake of readability). I additionally want to make it into an if, else if, else statement to test if the variable is empty/null.
This is what I have, which doesn't work:
if (_newText = null) {
'Invalid Record';
}
else if (_newText === a[textProp]) {
'no change';
}
else(_newText != a[textProp]) {
'changed';
}
+ ')';
if (_newText = null) {
^
needs to be
if (_newText == null) {
^^
or
if (_newText === null) {
^^^
And you need to build up your string
a[textProp] = 'Invalid Record';
For the sake of readability, I'd start with something like this, where each state is checked explicitly (valid and changed):
var isValid = true;
if (_newText == null || _newText.trim().length === 0) {
isValid = false;
}
var hasChanged = false;
if (isValid && _newText !== a[textProp]) {
hasChanged = true;
}
if (!isValid) {
a[textProp] = 'Invalid Record';
}
else if (hasChanged) {
a[textProp] = _newText + ' (changed)';
}
else {
a[textProp] += ' (no change)';
}
But, I also think it's not right to store the result of the tests as a string inside a[textProp], it could invalidate future tests. I'd probably have separate keys for the test results (as a flag), e.g.: a.valid[textProp] and a.changed[textProp] (in this case, textProp can never be "valid" or "changed"). Even better would be to store the text in a[textProp].text, and the flags in a[textProp].valid and a[textProp].changed.

Categories

Resources