javascript regex validation if no content - javascript

I have the following validation on a form field:
$(".controlsphone input").blur(function() {
var ree = /^\d+$/;
if(ree.test(document.getElementById("register_telephone").value))
{
$(this).css('border-color','green');
$(this).siblings('.info').css('display','none');
$(this).siblings('.error').css('display','none');
$(this).siblings('.valid').css('display','inline-block');
$("#email_error401112").hide();
$('#registerErrors').hide();
}
else
{
$('#registerErrors').show();
$('#email_error401112').remove();
$('#registerErrors').append('<p id="email_error401112">Please enter a phone number</p>');
}
});
I would like to only validate the field if a number exists. The field is not required, but if there is content within the field, it needs to be valid (a number)
How does the above code look? Any ideas what i can do to implement this?
Cheers, Dan

Use
var ree = /^\d*$/;
because + stands for one or more, excluding zero.
while * stands for zero or more

Related

How to validate string with RegExp()

I have a problem that I want to validate input field using RegExp(). Allows entering digits, characters and special character "_" to get the last string: regex3_example. When pressing the space key, "_" will be displayed. Hope everybody help please. Thank you!
document.querySelector('#input').addEventListener('input', function () {
var text = this.value;
if (re.test(text)) {
console.log("Valid");
} else {
console.log("Invalid");
}
$(document).keypress(function (event) {
if (event.keyCode === 32) {
var re = new RegExp("^[a-zA-Z_]");
var insert_string = text+'_';
let insert_text = insert_string.trim();
$('#key').val(insert_string);
}
});
});
I don't use jquery, but i can help. If you don't need to process your input data but only validade for user, you can use the prop pattern in your HTML tag.
<input
type="text"
pattern="\w*_\w{1,}"
title="Try the pattern test_test"/>
In this case, when you click on Button submit, the page will prenvent this action and show in this input the message passed on the prop title.
Hope help you, see ya!

Partial Password Masking on Input Field

So I need to mask a SSN# input field, lets say the ssn is 123-45-6789, I need to display ***-**-6789 (real time as they enter each digit) but I still need to retain the original value to submit.
I got to the point where I can do that if the user strictly enters the value but it breaks if the user does anything else such as delete, or moving cursor to a random position and adds/deletes a number, copy pasting/deleting, etc. I really don't want to listen to a bunch of events to make this work if thats even possible.
I also tried having a div sit on top of the input field to display the masked ssn while the actual ssn was transparent/hidden behind it but again they lose the functionality of being able to add/delete/select delete/paste in random parts (other then when they start at the end) and also the cursor not totally in sync with the end of the ssn number (asterisk size was the issue). This also broke on some mobile browsers.
I also thought of having two separate input fields, one type password, and one type text sit right next to each other, but again highlighting and deleting/pasting between the two would be an issue.
Ideally if there was something out there to have an input field have two types, part of the value be type password and the rest be type text, that would be fantastic. Btw this is for react js app.
TLDR: Need a fully functional input field that will do password masking on only first 5 digits of ssn and be plaintext for last 4 digits (while having the full plaintext value available for submission).
Thanks!
This might be a little sloppy, but it works as you want it to, is all in one text field, returns the full accurate SSN (despite replacing first 5 values with bullet points), and allows for editing anywhere in the field.
<input type="password" id="ssn" maxlength=9 />
<script>
var ssn = document.getElementById('ssn');
ssn.addEventListener('input', ssnMask, false);
var ssnFirstFive = "";
var secondHalf = "";
var fullSSN = "";
function ssnMask(){
if (ssn.value.length <= 5){
ssn.type = 'password';
}
else{
detectChanges();
secondHalf = ssn.value.substring(5);
ssn.type = 'text';
ssn.value = "•••••";
ssn.value += secondHalf;
fullSSN = ssnFirstFive + secondHalf;
}
}
function detectChanges() {
for (var i = 0; i < 5; i++){
if (ssn.value[i] != "•"){
ssnFirstFive = ssnFirstFive.substring(0, i) + ssn.value[i] + ssnFirstFive.substring(i+1);
}
}
}
</script>
Essentially, every time the input is changed, it checks to see if it matches the first 5 from before, and if it doesn't, it will update the necessary characters.
You can use 3 different fields and make then password fields.
Add a focus handler that changes their type into text and a blur handler that changes them back to password.
You can combine them before submission or on the server.
#ssn1{width:25px;}
#ssn2{width:20px;}
#ssn3{width:35px;}
<input type="password" name="ssn" maxlength=3 id="ssn1" />
<input type="password" name="ssn" maxlength=2 id="ssn2"/>
<input type="password" name="ssn" maxlength=4 id="ssn3"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$('[name="ssn"]').focus(function() {
$(this).attr("type", "text")
});
$('[name="ssn"]').blur(function() {
$(this).attr("type", "password")
});
</script>
You can also write a pass handler to all a full SSN to be pasted in the first field and have all three fields get set.
This is the closest you are going unless you work with a single full text box and give the user the ability to mask and unmask the field.
In production apps, this actually the approach I take:
Masked:
Unmasked:
You can implement you own focus/blur functions to automatically unmask/mask the field as needed.
Achieve this using html data attributes.
i have used the same html tag and store actual value in html tag attribute (data-value) to use later on and store value to display in html tag attribute value.
Function to partial mask input value
function mask_field_value(obj, mask_letters_count=7){
mask_value = $(this).data('mask-value') || '';
unmask_value = $(this).data('unmask-value') || '';
if (obj.value.length <= mask_letters_count){
obj.type = 'password';
mask_value = obj.value;
$(this).data('mask-value', obj.value);
} else {
obj.type = 'text';
unmask_value = obj.value.substring(mask_letters_count);
obj.value = "*".repeat(mask_letters_count) + unmask_value;
$(this).data('unmask-value', unmask_value);
}
$(this).data('value', mask_value + unmask_value);
console.log($(this).data('value'));
}
Add an event on input fields to mask
$(document).ready(function () {
$(document).on('keyup', '.mask_input_display', function () {
mask_field_value(this);
});
});

JQuery Validation - How to add rules?

I was trying to validate a textbox input via jquery, but I don't know how to apply certain rules for this kind of situation.
Here is the deal: I want the textbox to accept only alphanumeric inputs (A-Z and 0-9) and using ' . ' as separators for certain cases. If the textbox has a value of 16 (in this case, then the user must've typed something like this: 67EA981XXVT110TP), then I want to validate to check if there's only letters and numbers in the input, but if the value is 19 (something like: 67EA.981X.XVT1.10TP) then it has to be checked to confirm that the separators are in the right position (every 4 character input) and if there is only alphanumeric values in the field.
This is what I was trying to do (I'm using Razer Engine View)
<script type="text/javascript">
$(function () {
$('#txtCode').blur(function () {
if ($('#txtCode').val().length > 19) {
alert('Invalid field input!')
}
else if ($('#txtCode').val().length >= 1 && $('#txtCode').val().length < 16) {
alert('Invalid field input!')
}
if ($('#txtCodVerificador').val().length == 16) {
//check if there is only numbers and letters in the field
}
if ($('#txtCodVerificador').val().length == 19) {
//check if there is only numbers and letters in the field and if the separators are in the right place (every 4 character input)
}
});
});
</script>
You have mentioned I'm using Razer Engine View so I assume this is asp.net-mvc. Your current implementation means that you need to repeat all you validation again on the server when you submit. To handle this all out of the box, add a RegularExpressionAttribute to your property
[RegularExpression(#"^[A-Z0-9]{16}|([A-Z0-9]{4}\.){3}[a-zA-Z0-9]{4}$", ErrorMessage = "...")]
public string Code { get; set; }
and in the view
#Html.TextBoxFor(m => m.Code)
#Html.ValidationMessageFor(m => m.Code)
If your view includes jquery.validate.js and jquery.validate.unobtrusive.js, then you get both client and server side validation (your $('#txtCode').blur(.. script is not required)
Credit to ArcaneCraeda's answer for the regex.
Give this a shot:
$(function () {
$('#txtCode').blur(function () {
if ($('#txtCode').val().match(/^[A-Z0-9]{16}$/)) {
console.log("Matches the 16");
}else if ($('#txtCode').val().match(/^([A-Z0-9]{4}\.){3}[a-zA-Z0-9]{4}$/)) {
console.log("Matches the 19");
}else{
console.log("Does not match!");
}
});
});
JSFiddle
If you have any questions about the regex, ask away!

validating specific email address in form with javascript

I'm setting up a form and in it I've already coded verifying that there is an entry in the email form box as you can see here
function checkMailing(){
//if we want to refer to the email field - which has the name 'email' - we would use the form variable (created above), as such:
//theForm.email
//you this with the name of any field iside of the form
//alert(theForm.email.value);
//use an if statement to check the value of the form
var mailingVal = theForm.mailing.value
mailingVal = trim(mailingVal);
if(mailingVal == "" ){
//error message
//add a dropshadow to the field (to highlight it)
theForm.mailing.style.boxShadow = "0px 0px 6px #01FFFF";
//from the form field, go up to the parent (the div with the class 'formbox', then inside of that for the div with the class 'fieldInfo', and change the text contents to be an error message
setMessage(theForm.mailing, "error", "You must enter an address");
/*theForm.email.parentNode.querySelector("div").innerHTML = "You must enter an email!";
theForm.email.parentNode.querySelector("div").className = "error";*/
}else{
//if the user entered an email (or in this anything) give them positive feedback
theForm.mailing.style.boxShadow = "";
setMessage(theForm.mailing, "correct", "Perfect");
/*theForm.email.parentNode.querySelector("div").innerHTML = "Perfect)"
theForm.email.parentNode.querySelector("div").className = "correct";*/
}
}
However I need it to also validate that it is a CERTAIN email address and not just any email address. For example it must be an #gmail.com address and not an #hotmail.com or #anythingelse.com. Any guidance would be appreciated thank you!
You can use regex:
if (mailingVal && mailingVal.match(/#gmail\.com$/i)) {
// it's gmail
}
A better approach might be to use a regex which makes sure that the string to match ends with #gmail.com
var re = /#gmail\.com$/i;
if(re.exec(mailingVal) !== null) {
// the test passed!
}
This will ensure that the string ends with #gmail.com and does not contain any extra characters after the .com
Using that regex, someone#gmail.com will match, but someone#gmail.comm will not. As will someone#Gmail.com or someone#GMAIL.COM (and so on) because of the /i switch.
If you wanted it to only match case-sensitively, just remove the /i switch, so the regex would read like
var re = /#gmail.com$/
Update
Here is the regex solution in your code, changed the exec to test (which just returns true or false, depending on whether the regex matches or not):
function checkMailing(){
//if we want to refer to the email field - which has the name 'email' - we would use the form variable (created above), as such:
//theForm.email
//you this with the name of any field iside of the form
//alert(theForm.email.value);
//use an if statement to check the value of the form
var mailingVal = theForm.mailing.value,
re = /#gmail\.com$/i;
mailingVal = trim(mailingVal);
if(!re.test(mailingVal)){
//error message
//add a dropshadow to the field (to highlight it)
theForm.mailing.style.boxShadow = "0px 0px 6px #01FFFF";
//from the form field, go up to the parent (the div with the class 'formbox', then inside of that for the div with the class 'fieldInfo', and change the text contents to be an error message
setMessage(theForm.mailing, "error", "You must enter an address");
/*theForm.email.parentNode.querySelector("div").innerHTML = "You must enter an email!";
theForm.email.parentNode.querySelector("div").className = "error";*/
} else {
//if the user entered an email (or in this anything) give them positive feedback
theForm.mailing.style.boxShadow = "";
setMessage(theForm.mailing, "correct", "Perfect");
/*theForm.email.parentNode.querySelector("div").innerHTML = "Perfect)"
theForm.email.parentNode.querySelector("div").className = "correct";*/
}
}
This should work for you. I do have one question about the trim() function you are using. What is it? Is there a library you are using, or is the trim function something you wrote? I would just use String.prototype.trim to remove whitespace from the beginning and end of the mailingVal.
If you know wich exactly mail vendor you want to check, then try this one:
if (mailingVal.length && mailingVal.indexOf('#gmail.com') > -1 ) console.log('that is gmail!');
You also may need to put your string to lover case to be sure that 'Gmail' is also valid
mailingVal = mailingVal.toLowerCase()
UPD:
as metioned in comments, this case will make mails like 'wut#gmail.commadot' also valid.
To prevent that you can try this check:
mailingVal = mailingVal.split['#'];
if (mailingVal.length > 2) {
console.log('not Valid email');
} else {
if (mailingVal[1].toLowerCase() === 'gmail.com') console.log('Bingo!');
}

Javascript: Field validation

so i have been looking all over the internet for some simple javascript code that will let me give an alert when a field is empty and a different one when a # is not present. I keep finding regex, html and different plugins. I however need to do this in pure Javascript code. Any ideas how this could be done in a simple way?
And please, if you think this question doesn't belong here or is stupid, please point me to somewhere where i can find this information instead of insulting me. I have little to no experience with javascript.
function test(email, name) {
}
Here if you want to validate Email, use following code with given regex :
<input type="text" name="email" id="emailId" value="" >
<button onclick = "return ValidateEmail(document.getElementById('emailId').value)">Validate</button>
<script>
function ValidateEmail(inputText){
var mailformat = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if(inputText.match(mailformat)) {
return true;
}
else {
alert("You have entered an invalid email address!");
return false;
}
}
</script>
Or if you want to check the empty field, use following :
if(trim(document.getElementById('emailId').value)== ""){
alert("Field is empty")
}
// For #
var textVal = document.getElementById('emailId').value
if(textVal.indexOf("#") == -1){
alert(" # doesn't exist in input value");
}
Here is the fiddle : http://jsfiddle.net/TgNC5/
You have to find an object of element you want check (textbox etc).
<input type="text" name="email" id="email" />
In JS:
if(document.getElementById("email").value == "") { // test if it is empty
alert("E-mail empty");
}
This is really basic. Using regexp you can test, if it is real e-mail, or some garbage. I recommend reading something about JS and HTML.
function test_email(field_id, field_size) {
var field_value = $('#'+field_id+'').val();
error = false;
var pattern=/^([\w-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
if(!pattern.test(field_value)){
error = true;
$('#'+field_id+'').attr('class','error_email');
}
return error;
}
This will check for empty string as well as for # symbol:
if(a=="")
alert("a is empty");
else if(a.indexOf("#")<0)
alert("a does not contain #");
You can do something like this:
var input = document.getElementById('email');
input.onblur = function() {
var value = input.value
if (value == "") {
alert("empty");
}
if (value.indexOf("#") == -1) {
alert("No # symbol");
}
}
see fiddle
Although this is not a solid soltuion for checking email addresses, please see the references below for a more detailed solution:
http://www.regular-expressions.info/email.html
http://www.codeproject.com/Tips/492632/Email-Validation-in-JavaScript
---- UPDATE ----
I have been made aware that there is no IE available to target, so the input field needs to be targeted like so:
document.getElementsByTagName("input")
Using this code will select all input fields present on the page. This is not what are looking for, we want to target a specific input field. The only way to do this without a class or ID is to selected it by key, like so:
document.getElementsByTagName("input")[0]
Without seeing all of your HTML it is impossible for me to know the correct key to use so you will need to count the amount of input fields on the page and the location of which your input field exists.
1st input filed = document.getElementsByTagName("input")[0]
2nd input filed = document.getElementsByTagName("input")[1]
3rd input filed = document.getElementsByTagName("input")[2]
4th input filed = document.getElementsByTagName("input")[3]
etc...
Hope this helps.

Categories

Resources