Javascript regex validation? - javascript

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.

Related

jQuery Regex Check on field works but alert message doesn't change

I have this function to validate postcodes (UK):
/* validate Post Code */
$.fn.validatePostCode = function(postcode)
{
regex = /^[A-Za-z]{1,2}\d{1,2}\s*\d{1}[A-Za-z]{2}$/i;
if (!regex.test(postcode)) {
return false;
}
};
as you can see it's just a simple regex checking for amount of character types at certain points.
To trigger it (or at least in the part I'm using it for) I use:
$(document).ready(function()
{
$('#nextBtn').on('click', function()
{
var postcode = $('#postcode').val();
console.log(postcode);
if (!$.fn.validatePostCode(postcode)) {
alert('hi');
} else {
alert('not valid');
}
});
});
doing the console.log is so I can see the value of the postcode each check, and I can see it updates. However, upon changing the input so I know it should be wrong still alert('hi') instead of Not Valid. I've even added a console.log in my validate function and that shows when the postcode is invalid, so why doesn't the alert message change each click?
I used this to validate my regex: http://www.regextester.com/ and it said my pattern was ok when I typed various postcodes in, so I'm a little lost at the moment, any ideas?
Thanks
Ok, so I found the solution rather quickly - it's because my function doesn't return a value until it fails. Needed to add a return true; outside of the if statement.
Hope this helps anyone who has a similar problem :)

JQuery Validate Regex Password Validation

I have been reading about how to manipulate regex, and I do think I have the correct formula for my purpose, but I cannot seem to get it to work.
This is my code
$.validator.addMethod("pwcheck", function(value) {
var regex = /^[a-zA-Z0-9]*$/;
if (!regex.test(value)) {
return false;
}
});
I added this method to my password in the .validate({rules{}});
It is linked properly, but whatever I input in the text box I get the message I wrote in the .validate({messages{}});
the user should be only allowed to input letters and numbers, and seeing other methods posted on this site I tried to mimic and copy them, but it isn't working.
$.validator.addMethod("pwcheck", function(value) {
return /^[A-Za-z0-9]*$/.test(value)
});

JavaScript/jQuery - Validating based on length

I'm working on a simple form that I need to validate against UK postcodes. No problem there but I need to validate depending on the character length. The user can input only the first half of a postcode (i.e. SW1) or a full postcode (i.e. SW1 1AB).
I thought the best approach would be to check the length on KeyPress and validate against RegEx for either half a postcode or the whole thing. See below:
jQuery('.ValPostCode').keyup(
function(){
if (jQuery(this).length < 5){
jQuery.validator.addMethod("ValPostCode", function(value, element) {
return this.optional(element) || /([A-PR-UWYZa-pr-uwyz]([0-9]{1,2}|([A-HK-Ya-hk-y][0-9]|[A-HK-Ya-hk-y][0-9]([0-9]|[ABEHMNPRV-Yabehmnprv-y]))|[0-9][A-HJKS-UWa-hjks-uw]))/.test(value);
}, "Please enter a valid postcode");
} else if (jQuery('.ValPostCode').length > 4) {
jQuery.validator.addMethod("ValPostCode", function(value, element) {
return this.optional(element) || /^(GIR\\s{0,1}0AA|[A-PR-UWYZ]([0-9]{1,2}|([A-HK-Y][0-9]|[A-HK-Y][0-9]([0-9]|[ABEHMNPRV-Y]))|[0-9][A-HJKS-UW])\\s{0,1}[0-9][ABD-HJLNP-UW-Z]{2})$/.test(value);
}, "Please enter a valid postcode");
}
});
So, if the char length of .ValPostCode is less than 5 it validates only for the first half of a UK postcode, else it checks for a full and valid UK postcode.
At one point I was outputting the length of .ValPostCode but it always stopped at 1 (first keypress) and then didn't carry on any further (i.e. wouldn't count up with subsequent keypresses).
I hope I've explained myself clearly enough, please let me know if I'm not being clear.
I've searched for similar problems to try and fix this for myself but I couldn't find anything. Any help appreciated!
The length of $(selector).length (or jQuery(selector).length) will always be the number of elements on the screen that match the given selector. Try using $(selector).val().length to get the value of a form element and check its lenght instead.
It seems as though you are setting up validator rules on every keypress unnecessarily
When the page first loads, you should only need to call something like this:
jQuery.validator.addMethod("ValPostCode", function(value, element) {
if(value.length < 5) {
return (insert partial postcode check here);
} else {
return (insert whole postcode check here);
}
}, "Please enter a valid postcode");
And should only call it once. JQuery will pick up the error on submit/change depending on how it is configured.
So there is no need for a keyUp event.
The main problem you were having (as someone else has already pointed out) is that you were returning the length of the jQuery object rather than the length of its value attribute.

Javascript prompt/textbox only numbers

Hey guys I'm just learning javascript, I have some html and css background though.
I can't figure out how to allow only number values to be entered into a prompt, or check if its a number or not than re prompt if its not. Also the same goes for a textbox.
here is a good number testing function I use in a bit of my code (from Validate decimal numbers in JavaScript - IsNumeric()). It will return true if number, false if not. This is floating point validation, not integer
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
You already have a good answer. This answer is another look at things you can do.
Assuming your number field is like the following
<input type="text" name="num_fld" id="num_fld" onchange="return chkNum();" />
and you've defined a javascript function like so
function chkNum()
{
var rc = false;
if(!isNaN(parseFloat(n)) && isFinite(n))
{
rc = true;
}
else
{
document.getElementById("num_fld").value = 0;
}
return rc;
}
This function checks to see if the number is really a number, but also monkeys with the input, so the bad value does not stay in place. Offhand I am not quite sure if returning false prevents the number from being entered (kind of like in a validate function.) I believe from my testing that returning false does affect what is in the field, but I am not 100% sure of that.
You could also alter the background and/or text color of the input field upon failure (the else part of the test, so the user notices something is wrong. alert(); is good for testing, but kind of messes up the look of your site in production.

What JavaScript functions exist that I can use to check that an email and phone # are valid without resorting to a jquery plugin?

On a form, I need to make sure that all fields are filled in and that the phone # and email address are valid. I tried using a jQuery validation plugin but it changed the page's look and feel. The plugin also was dynamically looking for some css files in some spot that was unexpected.
I love jQuery but the plugin seemed too much for what I wanted.
Since all I need to do is to make sure the fields are not empty and that the phone number is valid and email is valid, what javascript functions do you suggest? I will still use jQuery core.
Serverside we want to use apache commons PhoneNumberFormatter and same with email validation.
Thanks!
I think you're looking for JavaScript regular expressions, using the RegExp object that comes as a standard part of JavaScript. You can use that to perform basic checking of email addresses and phone numbers.
e.g.
function emailIsValid(emailAddress) {
var emailRegex = /\b[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}\b/;
return !!emailAddress.match(emailRegex);
}
The code above is not tested, but it should give you an idea of how to do it. Just do the same again for the telephone number, and then do something like this:
if (emailIsValid(emailAddressValue) && telephoneNumberIsValid(telephoneValue)) {
//Submit form
} else {
alert ("There are errors on the form, please correct and invalid data");
}
In this jsfiddle you'll find a JQueryless method I use to check form fields. It checks all form fields periodically using an interval function.
Everyone focused on the email and phone number validation, but encase you need help with detecting empty text boxes and even just how/when to call the code for email/phone validation:
<script type="text/javascript">
function validate()
{
var curVal;
for(var index = 1 ; index < 15 ; index++)
{
curVal = document.getElementById("textbox_"+index).value
if(curVal == "")
{
alert("empty text box")
return(false); //false will stop the form from submitting
}
if(index = 5)// email text box
{
//validate email
}
}
}
</script>
<type="input" id="textbox_1">
<type="submit" value="Submit" onClick="validate()">
here is one for email
function checkemail()
{
var str=email
var filter=/^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z] {2})?)$/i
if (filter.test(str))
testresults=true
else
{
alert("Please input a valid email address!")
testresults=false
}

Categories