Javascript How To Evaluate On Number or Specific String - javascript

I need to evaluate a form submission to either be
"TBD" or a number > 0 . Is there a way to do that that I'm not seeing.. here is what I have so far:
<script language="Javascript">
function validateForm(){
//Declare Variables
var aa=document.forms["form"]["irnumber"].value;
if (aa =='TBD'){
return true;
}else if (parseInt(aa) < 1 || aa==null || aa=="") {
alert("IR Must Be A Number Or \"TBD\" ");
return false;
}
</script>
Any help is very much appreciated.

if (parseInt(aa) > 0 || aa === "TBD") {
return true;
} else {
alert("IR Must Be A Number Or \"TBD\" ");
return false;
}
or
if (/^((TBD)|(0*[1-9]+[0-9]*))$/i.test(aa)) {
return true;
} else {
alert("IR Must Be A Number Or \"TBD\" ");
return false;
}

Related

code does not validate email from a form, in javascpricpt

hi i font know if this is the right place to ask this question but i have a problem with my code that i cannot figure out. i have tried many different algorithms and none work. i am trying to validate email from a form.
here is the code (form is in html)
function isValidString(str) {
var quot = "\"";
if (str.indexOf(quot) != -1)
return false;
var badStr = "$%^&*()_+[]{}<>?אבגדהוזחטיכךלמםנןסעפצקרשת";
var i = 0,
p;
while (i < str.length) {
p = badStr.indexOf(str.charAt(i));
if (p != -1)
return false;
i++;
}
return true;
}
function isValidEmail()
{
var str = document.getElementById("email").value;
document.write("email from isValidEmail(str) = " + email);
if (isEmpty(str) || str.length < 5) {
alert("isEmpty(str) || str.length < 5 = false");
return false;
}
if (!isValidString(str)) {
alert("!isValidString(str) = false");
return false;
}
var atSign = str.indexOf('#');
if (atSign == -1 || str.lastIndexOf('#') || atSign === 0 || atSign == str.length - 1) {
alert("atSign == -1 || str.lastIndexOf('#') || atSign == 0 || atSign == str.length - 1 = false");
return false;
}
var dotSign = str.indexOf('.', atSign);
if (dotSign == -1 || dotSign === 0 || dotSign == str.length - 1 || dotSign - atSign < 2) {
alert("dotSign == -1 || dotSign == 0 || dotSign == str.length - 1 || dotSign - atSign < 2 = false");
return false;
}
return true;
no matter what i input it always comes back valid.
here is the part where i apply it:
var email = document.getElementById("email").value;
if (emailcheck(email)) {
alert("invalid email");
return false;
}
return true;
thanks in advance
An example of using the parser library mentioned in my comment.
var eAddr = document.getElementById('eAddr'),
check = document.getElementById('check'),
pre = document.getElementById('out');
check.addEventListener('click', function (evt) {
pre.textContent = !!emailAddresses.parseOneAddress(eAddr.value.trim());
}, false);
<script src="https://rawgit.com/FogCreek/email-addresses/master/lib/email-addresses.js"></script>
<input id="eAddr"></input>
<button id="check">Test pattern</button>
<pre id="out"></pre>
Note: this will accept Goodhertz Inc <support#goodhertz.com> as it stands and you would need to further check the object returned by parseOneAddress to filter these out.
You don't call the rigth function i. e. call
var email = document.getElementById("email").value;
if (isValidString(email)) {
alert("invalid email");
return false;
}
return true;
instead of
var email = document.getElementById("email").value;
if (emailcheck(email)) {
alert("invalid email");
return false;
}
return true;
Using Regular expression is the best method for validating input elements. Below function can validate email perfectly.
function regExValidate_Email(id) {
var email = document.getElementById(id).value;
if (email != '') {
var regExforEmail = /^[a-zA-Z0-9._+-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
if (regExforEmail.test(email)) {
$("#" + id).css("background-color", "#ffffff");
return true;
}
else {
alert('Please enter a valid email id. \nex: yourname#example.com');
document.getElementById(id).style.backgroundColor = '#feffea';
document.getElementById(id).value = '';
Ctrlid = id;
setTimeout("document.getElementById(Ctrlid).focus()", 1);
return false;
}
}
else { document.getElementById(id).style.backgroundColor = 'white'; }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
Email: <input type="email" onblur="return regExValidate_Email(this.id)" id="txtEmail" />

How does jQuery Validation setups the validation message?

I wrote an additional method for jquery validation plugin that checks if a given value meets the length requirements defined along with the validation process.
So the method looks like this:
jQuery.validator.addMethod("exactLength", function(value, element, param){
var len = value.length;
if ($.isArray(param)){
if (param.indexOf(len) !== -1){
return true;
} else {
return false;
}
} else {
if (param != len){
return false;
} else {
return true;
}
}
}, jQuery.format("Value must have {0} characters"));
It works but the only problem is that message sent to the user doesn't meet my needs. The reason why is because one field might have more than 1 valid length.
A bank code can have 8 or 11 digits.
So, if I define the options below I expect the following output in case of error:
"Please, the value must have 8 or 11 digits."
{
"options":{
"rules": {
"inputx": {
"required": true,
"exactLength": [8,11]
}
}
}
}
But I want more flexibility because i can have 2 values defined as valid lengths, "Please, the value must have 8, 11, xxx or 23 digits"
Or i can basic field where the input must have only 1 specific length "please, the value must have 8 digits"
So, inside the method is it possible to tell want should be passed to the message?
EDIT:
Added full solution based on Arun P Johny answer
jQuery.validator.addMethod("exactLength", function(value, element, param){
var len = value.length;
if ($.isArray(param)){
if (param.indexOf(len) !== -1){
return true;
} else {
return false;
}
} else {
if (param != len){
return false;
} else {
return true;
}
}
}, function(param, element){
var str = "";
if ($.isArray(param)){
var paramLen = param.length,
lastParamValue = param[ paramLen - 1];
if (paramLen == 2){
str = param[0];
} else {
for(var i = 0; i< paramLen - 1; i++){
if (i == paramLen - 1){
str += ',' + param[i];
} else {
if (i == 0)
str += param[0];
else
str += ',' + param[i];
}
}
}
return jQuery.format("Value must have {0} or {1} characters", str, lastParamValue );
} else {
return jQuery.format("Value must have {0} characters", param )
}
});
The message option can be a function so
jQuery.validator.addMethod("exactLength", function (value, element, param) {
var len = value.length;
if ($.isArray(param)) {
if (param.indexOf(len) !== -1) {
return true;
} else {
return false;
}
} else {
if (param != len) {
return false;
} else {
return true;
}
}
}, function (param, element) {
//you can customize the string generation here, params refers to the array passed to the rule
return "Value must have " + param.join(',') + " characters"
});
Demo: Fiddle

Javascript: multi-tiered conditional, use of "return false" stopping later conditional checks

Return false isn't doing quite what I want it to do. I want it to prevent the form submit if any one of the conditionals passes, but I still want it to proceed down the tree of conditionals. Right now if the first conditional if ($(".item.active").length == 0) { passes, it hits the return false; and stops the later conditionals from checking.
How can I rewrite this to work better?
$('#go').click(function() {
function invalidBtn(){
$('#go').addClass('invalid');
setTimeout(function() {
$('#go').removeClass('invalid');
}, 5000)
}
$('.error').remove();
$('.invalid').removeClass('invalid');
if ($(".item.active").length == 0) {
$(".item:first-of-type").before('<h5 class="error">Select a shirt type</h5>');
invalidBtn();
return false;
} else {
if ( $(".item.active .size-select .active").length == 0) {
$('.item.active .size-select').before("<div class='error'>Select a size</div>").addClass("invalid");
//$(this).addClass('invalid');
invalidBtn();
return false;
}
if ($(".item.active .gender-select").length > 0 ) {
if ( $(".item.active .gender-select .active").length == 0 ){
$('.item.active .gender-select').before("<div class='error'>Select a gender</div>").addClass("invalid");
//$(this).addClass('invalid');
invalidBtn();
return false;
}
}
}
if ( !$('#fn-field').val() ) {
$('#fn-field').before("<div class='error'>Enter your first name</div>").addClass("invalid");
//$(this).addClass('invalid');
invalidBtn();
return false;
}
if ( !$('#ln-field').val() ) {
$('#ln-field').before("<div class='error'>Enter your last name</div>").addClass("invalid");
//$(this).addClass('invalid');
invalidBtn();
return false;
}
});
Thanks so much
Simply replace all of your return false to change a boolean, and return the boolean, like this:
$('#go').click(function() {
function invalidBtn(){
$('#go').addClass('invalid');
setTimeout(function() {
$('#go').removeClass('invalid');
}, 5000)
}
var retVal = true;
$('.error').remove();
$('.invalid').removeClass('invalid');
if ($(".item.active").length == 0) {
$(".item:first-of-type").before('<h5 class="error">Select a shirt type</h5>');
invalidBtn();
retVal = false;
} else {
if ( $(".item.active .size-select .active").length == 0) {
$('.item.active .size-select').before("<div class='error'>Select a size</div>").addClass("invalid");
//$(this).addClass('invalid');
invalidBtn();
retVal = false;
}
if ($(".item.active .gender-select").length > 0 ) {
if ( $(".item.active .gender-select .active").length == 0 ){
$('.item.active .gender-select').before("<div class='error'>Select a gender</div>").addClass("invalid");
//$(this).addClass('invalid');
invalidBtn();
retVal = false;
}
}
}
if ( !$('#fn-field').val() ) {
$('#fn-field').before("<div class='error'>Enter your first name</div>").addClass("invalid");
//$(this).addClass('invalid');
invalidBtn();
retVal = false;
}
if ( !$('#ln-field').val() ) {
$('#ln-field').before("<div class='error'>Enter your last name</div>").addClass("invalid");
//$(this).addClass('invalid');
invalidBtn();
retVal = false;
}
return retVal;
});
Return false isn't doing quite what I want it to do. I want it to prevent the form submit if any one of the conditionals passes, but I still want it to proceed down the tree of conditionals. Right now if the first conditional if ($(".item.active").length == 0) { passes, it hits the return false; and stops the later conditionals from checking.
Right, because return exits the function.
If you want to keep going through the code following it, don't use return, set a variable you return at the end. E.g.:
var valid = true;
if (someInvalidCondition) {
// ...do anyting condition-specific...
valid = false;
}
if (someOtherInvalidCondition) {
// ...do anyting condition-specific...
valid = false;
}
// Rinse, repeat
// Done
return valid;
Or I usually like to return a count of the errors. Or a list (array) of the errors. Etc.

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.

Getting Jquery code to stay after form has finished submitting

My code Jquery code adds text to a table when a user makes a mistake in their form. However the text dissapears once it has finished checking and thus only appears for a brief split second.
Here is the Username validator:
function validateUserName()
{
var u = document.forms["NewUser"]["user"].value
var uLength = u.length;
var illegalChars = /\W/; // allow letters, numbers, and underscores
if (u == null || u == "")
{
$("#ErrorUser").text("You Left the Username field Emptyyy");
return false;
}
else if (uLength <4 || uLength > 11)
{
$("#ErrorUser").text("The Username must be between 4 and 11 characters");
return false;
}
else if (illegalChars.test(u))
{
$("#ErrorUser").text("The Username contains illegal charectors men!");
return false;
}
else
{
return true;
}
}
To prevent the form submission, you need to prevent the default action. Give this way:
function validateUserName(e)
{
e.preventDefault();
var u = document.forms["NewUser"]["user"].value;
var uLength = u.length;
var illegalChars = /\W/; // allow letters, numbers, and underscores
if (u == null || u == "")
{
$("#ErrorUser").text("You Left the Username field Emptyyy");
return false;
}
else if (uLength <4 || uLength > 11)
{
$("#ErrorUser").text("The Username must be between 4 and 11 characters");
return false;
}
else if (illegalChars.test(u))
{
$("#ErrorUser").text("The Username contains illegal charectors men!");
return false;
}
else
{
return true;
}
}
And you need to call the event this way:
$("form").onsubmit(validateUserName);
Update: Based on the comment.
Change your <form> tag markup this way:
<form name="NewUser" id="myform">
And in the JavaScript, use this way:
$("form").onsubmit(function(e){
e.preventDefault();
var u = document.forms["NewUser"]["user"].value;
var uLength = u.length;
var illegalChars = /\W/; // allow letters, numbers, and underscores
if (u == null || u == "")
{
$("#ErrorUser").text("You Left the Username field Emptyyy");
return false;
}
else if (uLength <4 || uLength > 11)
{
$("#ErrorUser").text("The Username must be between 4 and 11 characters");
return false;
}
else if (illegalChars.test(u))
{
$("#ErrorUser").text("The Username contains illegal charectors men!");
return false;
}
else
{
return true;
}
});
As already mentioned in the comment by #adeneo, you need to prevent your form from submitting.
<input type="submit" value="Submit" onclick="if(!validateUserName()) return false;"/>
This will prevent your form from submitting data if the form has errors. You already return true/false from your Javascript function, just utilizing those.

Categories

Resources