Struggling with some javascript, password / username error display - javascript

Note, I will validate everything with PHP on form submission, but I'd like to display it instantly to the user if possible.
For the username I am trying to detect if it only contains whitespace, if it's less than 8 chars/numbers and if it only contains normal valid letters and no symbols.
This does not seem to work:
$("#username").change(function() {
$("#username").removeClass("error");
var letterNumber = /^[0-9a-zA-Z]+$/;
var username = $("#username").val(); // get value of password
if (!(username.value.match(letterNumber)) {
// return error
}
if (username.length < 8) {
// return error
}
if (username.trim().length() > 0) {
// return error
}
});
And for the password, I want to allow all symbols, all numbers, all letters, minimum 8, and trim for whitespace. It does not seem to work though.

Change from this:
if (!(username.value.match(letterNumber)) {
// return error
}
to this:
if (!(username.match(letterNumber)) {
// return error
}
You've already retrieved the .value when you used .val() earlier so username is already the desired string.
Also, the .trim() test is not correct as .length is a property all by itself, not a method). But, you can just remove this because your regex test before has already eliminated empty strings and strings with only whitespace so this test (even when corrected to be proper javascript) is unnecessary.
if (username.trim().length() > 0) {
// return error
}
In the future, you should be looking in your browser error console or debug console because it would have told you something like undefined doesn't have a method .match() and given you that exact line number as the source of the error.

Related

Cannot compare String returned by out.print()

I am using jsp as a server side script with HTML/JQuery for the client end.
I am doing a AJAX to the jsp file and everything works ok.
The problem starts when I am trying to compare the string returned by out.print() from jsp with in the jquery ajax result. The comparison never seems to result true!
It seems the out.print() is prepending a number of /n to the string.
$.post("jsp/login.jsp", { msg: $email.val() + "~" + $pass.val() }, function (result) {
if (result === "OK")
alert("Logged in");
else
alert("Invalid Credentials");
});
It seems the out.print() is prepending a number of /n to the string.
In this case you have two options. First, you can remove the extra whitespace in JS before using the value in a condition:
if ($.trim(result) === "OK")
alert("Logged in");
else
alert("Invalid Credentials");
Alternatively, and preferably, you could change your JSP code to return JSON. By definition this cannot have extraneous whitespace added to the values of its properties.
Remember how Java object comparisons work. In java a string literal "OK" in this case is itself an object and has it's own location in memory. When you do a comparison with another string object, result in this case, you aren't comparing the actual value of the two strings as you would with primitive types you're comparing the object location in memory. As such, you could use something like compareTo which is associated with String, something like this.
//Compare to returns an int, -1 for less then, 1 for greater then and 0 for equals
if(result.compareTo("OK") == 0){
//Do your code here
}

javascript variables always not equal

I have two variables, totalGuess and condensedAnswer. I am creating a jQuery click event and if totalGuess doesn't equal condensedAnswer then the click event will not occur and a div called message will display the message "Sorry, but your answer is incorrect. Please try again."
The problem is, totalGuess in the if statement is never equal to condensedAnswer. I've tried seeing typeof and they are both strings. I've tried console.log(totalGuess+"\n"+condensedAnswer); and they both return the same value. I've tried hardcoding the condensedAnswer, and totalGuess was able to be equal to the hardcoded answer. But when I tried comparing condensedAnswer with the hardcoded answer, it's not equal, even though the console.log value for condensedAnswer is the same. I'm not what's wrong.
Here's the code snippet:
$('.submitGuess').click(function(e){
var totalGuess = "";
var condensedAnswer = answer.replace(new RegExp(" ","g"), "");
$('.crypto-input').each(function(){
totalGuess += $(this).val();
});
// if incorrect guess
if(totalGuess !== condensedAnswer) {
$('.message').text("Sorry, but your answer is incorrect. Please try again.");
e.preventDefault();
}
// if user wins, congratulate them and submit the form
else {
return true;
}
});
If it helps, here's the page, just a random test cryptogram plugin for Wordpress:
http://playfuldevotions.com/archives/140
The problem has nothing to do with the check. The problem is the fact your value you are checking against has hidden characters. However you are getting that string has the issue.
Simple debugging shows the problem
> escape(totalGuess)
"God%27sMasterpieceMatthew15%3A99Psalms129%3A158"
> escape(condensedAnswer)
"God%27sMasterpieceMatthew15%3A99Psalms129%3A158%00"
It has a null character at the end.
Now looking at how you fill in the answer you have an array with numbers
"071,111,100,039,...49,053,056,"
Look at the end we have a trailing comma
when you do a split that means the last index of your array is going to be "" and hence why you get a null.
Remove the trailing comma and it will magically work.

Using regex in javascript

I cannot get to work the following example of Regex in JavaScript. Regex is valid, was tested on some webs testing Regex expression.
I want it to check if input is in format: xxx,xxx,xxx.
It is alerting wrong input all the time. Thanks for any help.
var re = /[0-9a-zA-Z]+(,[0-9a-zA-Z]+)*/;
var toValidation = document.getElementsByName("txtSerial").value;
alert(toValidation);
if(!re.test(toValidation))
return true;
else
{
alert("Please insert valid text.");
return false;
}
document.getElementsByName("txtSerial") will return all elements by that name (node collection). Node collections do not have an attribute named value, thus, .value will be undefined (as can be seen by your alert).
Depending on your markup, you will want to use
document.getElementById("txtSerial")
or
document.getElementsByName("txtSerial")[0]
(although the last one is certainly not ideal).

Javascript regex validation?

So I'm using the minimal regex [0-9]* for the iPhone number pad in my HTML5 pattern attributes. I also had a submit function that sends an email through the server. Everything was working good until I realized it was trying to send the form re3gardless of whether the browser was trying to block submit based on incorrect user input.
So I did the following but can't get it to work:
<script>
function validate(){
var phone=/[0-9]*/;
var x=document.forms["form"]["contactnum"].value;
if (x!=phone){
alert("Contact Number must be a valid phone number (no dashes)");
return false;
}
else {
alert("Thank you! We have received your information and will contact you shortly.");
ajax('{{=URL('new_post')}}',['phone'], 'target');
return false;
}
}
</script>
The problem is I can only get it to work if I set if (x==null || x=="") in the if statement. If I try to match it with any other var it will always say I'm not matching the [0-9]*. I already have written several complex regex's but really don't want to use anything on this simple form. I just wanted the number pad on the iPhone and not to submit if it wasn't a digit or null. I don't even care if they put in a "2" for the phone, just so long as it's a digit.
Thanks.
if ( x.match(/^[0-9]+$/) ) {
// valid
} else {
// invalid
}
That's not how you use a regular expression:
if (!phone.test(x)) ...
Also if you want to match a string with nothing but digits, try
var phone = /^\d*$/;
That will match the empty string too; use + instead of * if you want at least one digit.
You actually seem to have two questions in one here. For the first part, you haven't shown how you're using validate(), but remember that the onsubmit handler, itself, must return false to keep the browser from completing the normal submit process. For example, the following will not work:
$('#myform').submit(function(){
validate();
});
But this would successfully stop the default submit process:
$('#myform').submit(function(){
return validate();
});
validate() would return false, and then your handler returns the same.

Check validation for numbers only

following is my piece of code which checks if the input format is EMAIL which comes from the form input or not and validates accordingly i want to know how can i modify the following code that validates if the input was only number
if(email.length == 0 || email.indexOf('#') == '-1'){
var error = true;
$('#email_error').fadeIn(500);
}else{
$('#email_error').fadeOut(500);
}
Use jQuery's IsNumeric method.
http://api.jquery.com/jQuery.isNumeric/
$.isNumeric("-10"); // true
if (email.match(/[0-9]+/)) {
//it's all numbers
}
EDIT
As mentioned in the comments, to ensure that the entry is ALL numbers, the regex would have to include the begin and end characters, ^ and $:
if (email.match(/^[0-9]+$/)) {
//it's all numbers
}
Or even more succinctly:
if (email.match(/^\d+$/)) {
//it's all numbers
}
I don't deserve the credit for that fix, but I did want to correct it for anyone who may come find this later.
I would use:
if(isNaN(email*1)){
//evaluated to NaN
}else{
//evaluated to number
}
In this case the (email*1) have the possibility to evaluate to NaN, and thus will fail the check because the list of falsish values are 0,"",false,null,undefined,NaN
Check if converting the email address to a Number object returns a 'Not a Number' value; if not, the input was a number. The code would look like this:
if(!isNaN(Number(email)) {

Categories