Validation not working (extjs) - javascript

I cannot get my code to work. The second if statement is not being read at all for some reason.
function validateStation(v){
// search store for value... if you find it then true, else false
if (storeStation.findExact('disp',v) > -1) return true;
else return 'This value is not valid.';
if (cbStationFSAC.isValid()) return true;
else return 'This value is not valid.';
}

The function rightfully exits the code after reading the first if/else statement.
Instead try rewriting the code as such
function validateStation(v){
// search store for value... if you find it then true, else false
if (((storeStation.findExact('disp',v) > -1) || (cbStationFSAC.isValid()))
return true;
else
return 'This value is not valid.';
}

You can do something like this so it executes all the condition before returning the value
function validateStation(v){
var output = true;
if (storeStation.findExact('disp',v) > -1)
output = true;
else
output = 'This value is not valid.';
if (cbStationFSAC.isValid())
output = true;
else
output ='This value is not valid.';
return output;
}

Related

error in javascript conditional statement

I am facing an issue in javascript. if key value is true they stop it return true whereas if key value is false they shows Error.
Problem: they don't read the condition number or name value in if body. if key value is true they terminate.
How should i handle this condition? that they should also read the condition number or name value in if body.
can i use else if statement here ?
var key = $('#key').val().trim();
if(key != "" ){
return true; //value is true if value is true they stopped it
}
if(key === ''){
showError(); //this field is required
return false;
}
//if key value is true they don't execute my number or name condition
if ( $('#number').val().trim() === '' || $('#name').val().trim() === '' )
{
if ($('#number').val().trim() === '') {
showError(); //this field is required
}
if ($('#name').val().trim() === '') {
showError(); //this field is required
}
return false;
}
else{
return true; //always return true
}
how can i do? anyone help me?
Not sure if this is what you wanted. Have a look. The code continues after checking key.
var key = $('#key').val().trim();
if(key === ''){
showError(); //this field is required
let keyStat = false;
}
//if key value is true they don't execute my number or name condition
if ( $('#number').val().trim() === '' || $('#name').val().trim() === '' || keyStat === false) {
if ($('#number').val().trim() === '') {
showError(); //this field is required
}
if ($('#name').val().trim() === '') {
showError(); //this field is required
}
if (!keyStat) {
showError(); //this field is required
}
return false;
}
else{
return true; //always return true
}
when you call return statement your function will exit,only code before the return statement will run
Example:
function bar(){
var key = 12
if(key === 12){
console.log("only code before the return statement will run")
return true; // when you call return your function will exit
}
console.log("this will be terminated")
}
click me

how to check the return from function

i'm new to programming , i don't understand this line if(!validateform(siteName,siteURL)) ,what happens if function return false , will it enter the if condition ???
if(!validateform(siteName,siteURL))
return false;
// Validate Form
function validateForm(siteName, siteUrl){
if(!siteName || !siteUrl){
alert('Please fill in the form');
return false;
}
var expression = /[-a-zA-Z0-9#:%_\+.~#?&//=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9#:%_\+.~#?&//=]*)?/gi;
var regex = new RegExp(expression);
if(!siteUrl.match(regex)){
alert('Please use a valid URL');
return false;
}
return true;
}
If the function returns false it will enter the if condition, but if the function returns true it won't enter the if condition. This is because you are using the not operator (!).
The not operator simply makes a boolean true value into a false value and a false to a true value.
Firstly there is an error in the line you want to know about when you're calling a function remember it is case-sensitive. Your function is defined as validateForm but you are calling it with validateform.
That aside the below snippet is an attempt to explain what the function does during runtime.
in the below snippet
if(!validateForm(siteName,siteURL))
what this line does is it calls the function validateform() and passes the arguments siteName and siteURL . The function performs certain validations on the parameters and depending on the outcome of the validating statements(commented below) it returns true or false. The condition in the if statement !validateForm(siteName,siteURL) checks to see if the output of the function is false (ie return false;). If it is false it will execute the if statement(remember this depends on the parameters passed). You can see the examples in the snippet to see when the statement returns true/false.
function checkURL(siteName, siteUrl) {
if (!validateForm(siteName, siteUrl)) {
console.log("invalid name " + siteName);
console.log("invalid URL " + siteUrl);
return false;
} else {
console.log("Site name is valid " + siteName);
console.log("Site URL is valid " + siteUrl);
}
}
// Validate Form
function validateForm(siteName, siteUrl) {
if (!siteName || !siteUrl) { //validating statement 1
alert('Please fill in the form');
return false;
}
var expression = /[-a-zA-Z0-9#:%_\+.~#?&//=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9#:%_\+.~#?&//=]*)?/gi;
var regex = new RegExp(expression);
if (!siteUrl.match(regex)) { //validating statement 2
alert('Please use a valid URL');
return false;
}
return true;
}
console.log("URL and name valid");
checkURL("stackoverflow","https://www.stackoverflow.com");
console.log("URL invalid")
checkURL("stackoverflow","stackoverflow");
console.log("Name not defined");
checkURL(undefined,"https://www.stackoverflow.com");
console.log("URL not defined");
checkURL("stackoverflow",undefined);

phone number validation wont pass

function ClientContactCheck(){
var clientcontact = $("#client_contact_id").val();
if(clientcontact.length != ""){
if(!isNaN(clientcontact)){
$("#client_contact_id").css('border-color', "#dfe0e6");
return true;
}
}else{
$("#client_contact_id").css('border-color', "red");
}
return false;
}
i am using this function to validation phone number , my intention is simple just not be empty and must be number.
but if put !isNaN and my input was 123-456-789 , it wont valid cause the - was not a number, how to i make my function bypass the - ?
so if the input value had - it will pass thought.
thank
You can use :
str.replace("-", "");
and then check your input if it is a number only.
Edit:
var res = str.replace(/\-/g,'');
You can check it with a regular expression:
var clientcontact = $("#client_contact_id").val();
if (/^[0-9\-]+$/.test(clientcontact)) {
$("#client_contact_id").css('border-color', "#dfe0e6");
return true;
} else {
$("#client_contact_id").css('border-color', "red");
return false;
}
This will allow '-', '--', '---' too. If that is not desired, you can do one more check: ... && !/^-*$/.test(clientcontact)
You can do something like this to validate the phone number.
function phonenumber(inputtxt)
{
var phoneno = /^\+?([0-9]{2})\)?[-. ]?([0-9]{4})[-. ]?([0-9]{4})$/;
if((inputtxt.value.match(phoneno))
{
return true;
}
else
{
alert("message");
return false;
}
}
More at http://www.w3resource.com/javascript/form/phone-no-validation.php

Validate forms using javascript

I want to validate 3 inputs (name, email and password) in a form using javascript. When the user submits the form, and all the fields are empty, it works correctly showing the error messages. But then if I write a correct password (length 7) and wrong email and name, and I try to submit the form again the "Password too short" message is stil there and the password is correct. What I am doing wrong?
Javascript file
function verify(){
if(verName()&verEmail()&verPassword())
{
return true;
}else
{
verName();
verEmail();
verPassword();
return false;
}
}
function verPassword(){
var ok = true;
var frm = document.getElementById("register");
var pass = frm.elements[2].value;
if(pass.length<6)
{
var text="Password too short";
document.getElementById('textPassword').innerHTML=text;
ok = false;
}
return ok;
}
HTML file
<form id='register' name='register' onsubmit="return verify()">
function verify(){
document.getElementById('textPassword').innerHTML = ' ';
if(verName()&verEmail()&verPassword())
{
return true;
}else
{
verName();
verEmail();
verPassword();
return false;
}
}
change your code it like this:
function verify(){
if(verName()&verEmail()&verPassword())
{
return true;
}
else
{
if(verName());
if(verEmail());
if(verPassword());
return false;
}
}
with this solution, each validation occurs if the previous validation runs true! and if not, just the previous validation errors shows up !
in each function verName(), verEmail() and verPassword(), return Boolean value of TRUE of FALSE
also add this line of code, on your form submit event:
verify() {
document.getElementById('textPassword').innerHTML= ' '
....
....
}
The problem is that your verPassword function is adding that error string when the password is invalid, but it doesn't remove it when the password is valid.
Also, your verify function makes little sense.
How about:
function verify(){
return verName() && verEmail() && verPassword();
}
function verPassword(){
var frm = document.getElementById("register");
var pass = frm.elements[2].value;
var ok = pass.length > 5;
var text = ok ? "" : "Password too short";
document.getElementById('textPassword').innerHTML=text;
return ok;
}
You have to empty the #textPassword element by write something like: document.getElementById('textPassword').innerHTML.
In addition I can see some wrong codes there. First, if every ver* function returns true or false, you better use && rather than & in if condition expression. Or you can just return the evaluated value of the condition expression like this: return verName() && verEmail() && verPassword().
Second, the ver* functions are already called while if evaluate condition expression. No need to call those functions again in else part.
And I don't think you need ok variable in verPassword() function.
I suggest to change the code like below:
function verify(){
return verName() && verEmail() && verPassword();
}
function verPassword(){
var frm = document.getElementById("register");
var pass = frm.elements[2].value;
var textPassword = document.getElementById('textPassword');
if (pass.length < 6) {
var text="Password too short";
textPassword.innerHTML = text;
return false;
} else {
textPassword.innerHTML = ""; // Empty #textPassword
return true;
}
}

Javascript IF blocks get skipped

I'm using this code to validate a form:
if (isEmpty(email)) {
alert("1");
return false;
}
else if (!isEmail(email)) {
alert("2");
return false;
}
if (isEmpty(name)) {
alert("3");
return false;
}
if (isEmpty(age)) {
alert("4");
return false;
}
else if (!isAge(age)) {
alert("5");
return false;
}
if (isEmpty(city)) {
alert("6");
return false;
}
if (isEmpty(comments)) {
alert("7");
return false;
}
When hitting the "Submit" button, if the first two conditions do work(The ones that check if the email var is empty or not in email address format) - meaning that if I leave the email input empty or not in an email address format I get the alert (1 or 2).
The problem is that the rest of the validations get skipped and it doesn't matter if I leave another input empty or not in format.
Also, if I take the first IF block:
if (isEmpty(email)) {
alert("1");
return false;
}
else if (!isEmail(email)) {
alert("2");
return false;
}
And move it to the end of the validation block, everything works just fine.
I'm guessing I have a wrong syntax somewhere but I spent 2 hours looking and just couldn't find it.
P.S.
here are the two validation functions I'm using:
function isEmpty(field) {
if ((field == null || field == "")) {
return true;
}
return false;
}
function isEmail(field) {
var atpos = field.indexOf("#");
var dotpos = field.lastIndexOf(".");
if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= x.length) {
return false;
}
}
You use x.length in the isEmail function, but x is not defined.
the return statement exits the function to get all the validations run
keep all the validations in if else if blocks and keep on using return false every time.
or
set a variable to false whenever condition fails and then return the value. as j00lz said.
The
return false;
ends the function and stops the rest of the code being executed.
Instead set a variable:
result="false";
and at the end of the function add
return result;
What happens if you change it to this:
if (isEmpty(email)) {
alert("1");
return false;
}
else if (!isEmail(email)) {
alert("2");
return false;
}
else if (isEmpty(name)) {
alert("3");
return false;
}
else if (isEmpty(age)) {
alert("4");
return false;
}
else if (!isAge(age)) {
alert("5");
return false;
}
else if (isEmpty(city)) {
alert("6");
return false;
}
else if (isEmpty(comments)) {
alert("7");
return false;
}
I'm just curious as to what happens if you make the whole thing one big if statement rather than breaking it up into parts, considering it's not going to change the validation process.
P.S.
I'm not sure if you realize or not, but with the way you have it set up, once one of the first if statements comes back false, returning false with in that if statement will end the whole method you're working in, meaning it won't run any other parts of it. So if you're shooting for displaying an alert for each and every empty input, etc, it won't happen this way.

Categories

Resources