Javascript validating a text area to find a SSN - javascript

I am trying to create a quick validation of a text area notes field to see if it potentially contains a SSN number which I will then throw an alert for.
I have tried a few different RegEx patters I have found online and none of them seem to be working. I am wondering if its my javascript that isn't correct?
I believe if it were to find a match, it would be true thus throw the SSN Found alert.
Anyone point out my mistake?
$(document).ready(function() {
$('[name="submit"]').click(function() {
validate();
})
})
// Validate our note field
function validate() {
var isValid = true,
notes = $('[name=notes]').val(),
ssn = new RegExp('^(?!219-09-9999|078-05-1120)(?!666|000|9\d{2})\d{3}-(?!00)\d{2}-(?!0{4})\d{4}$');
console.log(notes)
if (ssn.test(notes)) {
alert('SSN Found');
}else{
alert('No SSN Found');
}
}
JS Fiddle: https://jsfiddle.net/sgrw4rqf/2/

You need to make your regex global rather than matching the SSN only.
Use something like this:
if ($('[name=notes]').val().match(/\b(?!219-09-9999|078-05-1120)(?!666|000|9\d{2})\d{3}-(?!00)\d{2}-(?!0{4})\d{4}\b/g)) {
and it will match as expected.

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 :)

javascript validation telephone

I have this function which objective is to validate a phone number introduced by a user with base in 2 regex variables.
if the user has the country Sweden selected and introduces 212341512 the warning shouldnt appear since the phone is valid however that doesnt happen. i still get the warning message to appear even if the phone number matches the conditions in the variable indicators.
function validateTelephone() {
var telephone = document.getElementById('txtTel');
var country=document.getElementById('ddCountry');
var indicators= /^(21|22)\d{7}$/;
if (country.value == "Sweden") {
if (!indicators.test(telephone.value)) {
document.getElementById('lblWarning').style.color = "red";
document.getElementById('lblWarning').innerHTML = 'Invalid Telephone Number';
} else {
document.getElementById('lblWarning').innerHTML = '';
}
} else{
document.getElementById('lblWarning').innerHTML = ' ';
}
}
if you guys have any suggestions about my code or a way to solve this problem i'd appreciate that since im new to this language
I would use libphonenumber, which has a JavaScript library already made for you.
https://code.google.com/p/libphonenumber/
As for your code, the regex is correct, and does match the number provided.
Please try using Chrome's JavaScript debugger. (right-click page, inspect element, sources tab). Put in a breakpoint at the beginning of your function and see what happens. Check the values of variables.

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 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.

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