Regex to allow only positive whole numbers and checking validity in jQuery - javascript

I have two input field like this in my HTML:
<input type="text" class="txtminFeedback" pattern="^\d+([\.\,][0]{2})?$" placeholder="Minimum Feedback">
<input type="text" class="txtmaxFeedback" pattern="^\d+([\.\,][0]{2})?$" placeholder="Maximum Feedback">
I've tried several regex patterns like following:
^\d+([\.\,][0]{2})?$
or
(^[0-9]+$|^$)
or
/^\d*$/
None of these worked whatsoever with the following code in jQuery:
if ($('.txtminFeedback').val() == "" && $('.txtmaxFeedback').val() == "") {
if ($('.txtmin')[0].checkValidity() && $('.txtmax')[0].checkValidity()) {
if ($('.txtSearch').val() == "") {
ShowMessage("Please enter the search term!");
return;
}
else {
PostAndUpdate($('.txtSearch').val(), $('input[name=type]:checked').val(), $('input[name=shipping]:checked').val(), $('input[name=condition]:checked').val(), $('.txtmin').val(), $('.txtmax').val(), $('.txtNegativeKeywords').val(), $('.txtminFeedback').val(), $('.txtmaxFeedback').val());
}
} else {
ShowMessage("You have entered incorrect value for minimum or maximum price!");
return;
}
} else if (!$('.txtminFeedback')[0].checkValidity() || !$('.txtmaxFeedback')[0].checkValidity())
{
ShowMessage("Please enter only positive value for minimum and maximum feedback.");
return;
}
User can leave the txtminfeedback and txtmaxfeedback empty if he wants. However if he decides to enter some values, then both fields must be entered and will require to have entered only whole positive numbers (from 0 to 4 million).
What am I doing wrong here?

In the end this did it:
pattern="^(\s*|\d+)$"
if ($('.txtminFeedback')[0].checkValidity()==false || $('.txtmaxFeedback')[0].checkValidity()==false) {
ShowMessage("Please enter only positive value for minimum and maximum feedback.");
return;
}
if ($('.txtmin')[0].checkValidity() && $('.txtmax')[0].checkValidity()) {
if ($('.txtSearch').val() == "") {
ShowMessage("Please enter the search term!");
return;
}
else {
PostAndUpdate($('.txtSearch').val(), $('input[name=type]:checked').val(), $('input[name=shipping]:checked').val(), $('input[name=condition]:checked').val(), $('.txtmin').val(), $('.txtmax').val(), $('.txtNegativeKeywords').val(), $('.txtminFeedback').val(), $('.txtmaxFeedback').val());
}
} else {
ShowMessage("You have entered incorrect value for minimum or maximum price!");
return;
}
Just in case someone in future might need it.
Cheers =)

Related

Getting function to run as user types

I have a phone number input that I am trying to get the dashes to appear in the number as the user types.
I am wanting the number to appear as 555-555-5555.
The function works for the most part, but the dashes aren't entered until after the whole number is entered. I am using the keyup function, which I thought would solve this, but no luck.
Does anyone have any recommendations as to what I have to do to get the dashes to be entered as the user types in the digits?
$('#phone').keyup(function() {
$(this).val($(this).val().replace(/(\d{3})\-?(\d{3})\-?(\d{4})/,'$1-$2-$3'))
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>
<label class="contact-label">Phone Number:</label>
<input type="tel" class="contact_input" name="phone" id="phone">
</div>
I modified your code slightly to produce something that I think is a little easier to read, but still does the job.
I just evaluated the length of the <input /> tag's value on each .keyup() event and then augmented the value accordingly. Take a look at the snippet below:
--UPDATE--
After comments regarding backspacing issues I added a couple lines of code that seem to fix the issue:
First I checked for either backspace or delete .keyup() events to prevent the formatting code from interfering with correcting errors in the number.
I also added a few checks, and a global formatFlag variable to ensure that if the user backspaces to an awkward index like 3 or 6(where hyphens would normally be added), that formatting would resume as normal on the next .keyup() event.
let formatFlag = false;
$(function(){
$('#phone').keyup(function(evt) {
let modifiedValue = $(this).val().replace(/-/g, "");
if(evt.keyCode == 8 || evt.keyCode == 46) { //8 == backspace; 46 == delete
//Checks whether the user backspaced to a hyphen index
if(modifiedValue.length === 3 || modifiedValue.length === 6) {
//Checks whether there is already a hyphen
if($(this).val().charAt($(this).val().length - 1) !== '-') {
formatFlag = true; //Sets the format flag so that hyphen is appended on next keyup()
} else {
return false; //Hyphen already present, no formatting necessary
}
} else {
formatFlag = false;
}
return false; //Return if backspace or delete is pressed to avoid awkward formatting
}
if(!!formatFlag) {
// This re-formats the number after the formatFlag has been set,
// appending a hyphen to the second last position in the string
$(this).val($(this).val().slice(0, $(this).val().length - 1) + '-' +
$(this).val().slice($(this).val().length - 1));
formatFlag = false; //Reset the formatFlag
}
if(modifiedValue.length % 3 == 0) {
if(modifiedValue.length === 0 || modifiedValue.length >= 9){
return false;
} else {
$(this).val($(this).val() + '-');
return;
}
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>
<label class="contact-label">Phone Number:</label>
<input type="tel" class="contact_input" name="phone" id="phone" />
</div>

Combining these two functions into one

Hey guys I have a password validator that I amd having issues working on, its quite lengthy and I think can be shortened down and simplified if possible.
Could someone assist me in simplifying it. Im talking about the checkValidPassword() function.
function check(input) {
if (input.value != document.getElementById('password').value) {
input.setCustomValidity('Password Must be Matching.');
} else {
// input is valid -- reset the error message
input.setCustomValidity('');
// check the length of the password
checkValidPassword(input);
}
}
function checkValidPassword(input) {
var password = document.getElementById('password');
var confirm_password = document.getElementById('confirm password');
if (password.value.length < 8) {
password.setCustomValidity('Password must contain at least 8 characters!');
} else {
var re = /[0-9]/;
if (!re.test(password.value)) {
password.setCustomValidity('password must contain at least one number (0-9)!');
} else {
password.setCustomValidity("");
}
}
}
And im trying to implement a way for the user to must include atleast a number also. I was thinking about
str.match(/^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])([a-zA-Z0-9]{8,})$/)
Would I include that in the if statment with $$ to symbolize and also check characters ?
if(password.value.length < 8 && str.match(/^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])([a-zA-Z0-9]{8,})$/)) {
This is essentially a code review question, but ok... I'd rewrite your function to something like:
function checkPassword() {
var password = document.getElementById('password');
var confirm_password = document.getElementById('confirm password');
if (password.value != confirm_password.value) {
password.setCustomValidity('Password Must be Matching.');
return false;
}
if(password.value.length < 8 ) {
password.setCustomValidity('Password must contain at least 8 characters!');
return false;
}
if(!/[0-9]/.test(password.value)) {
password.setCustomValidity('password must contain at least one number (0-9)!');
return false;
}
return true;
}
Basically, check each condition individually and return immediately if it fails, thus avoiding extra indentation ("early exits"). This is a bit verbose, but far more readable than a monster regular expression, especially if you don't know for sure what it does.
I managed to figure it out, I combined them both by just putting the else into one another.
function ValidatePassword(pass, confirm_pass) {
if (pass.value != confirm_pass.value || pass.value == "" || confirm_pass.value == "") {
confirm_pass.setCustomValidity("the Passwords do not match");
pass.setCustomValidity("the Passwords do not match");
} else {
if(pass.value.match(/(?=^.{8,30}$)([a-zA-Z]+[0-9])$/)) {
pass.setCustomValidity("");
confirm_pass.setCustomValidity("");
} else {
pass.setCustomValidity("the password doesnt have numbers");
confirm_pass.setCustomValidity("the password doesnt have numbers");
}
}
}
Here is what I made the form look like:
<form>
password
<input id="pass" type="password" required="" placeholder="Password" />
<br> confirm
<input id="confirm_pass" type="password" required="" placeholder="confirm" onfocus="ValidatePassword(document.getElementById('pass'), this);" oninput="ValidatePassword(document.getElementById('pass'), this);" />
<br> username :
<input id="username" required="" type="text">
<br>
<button class="btnform" name="register" type="submit">Complete Registration</button>
</form>

validating using input.value.match in javascript

I believe I have a fairly simple problem, but I am unfortunately unable to resolve it. I have searched for a while and tried several different variations of this code but cannot seem to get it to work.
All I am trying to do is check and see if my input value has a alpha character in it opposed to a number.
Here is my js function:
function checkLetters(input) {
var numOnly = /^[0-9]+$/;
var hasLetters = false;
if (!input.value.match(numOnly)) {
hasLetters = true;
}
return hasLetters;
}
and here is the code calling it:
<input type="text" name="cc_number" size="13" maxlength="11" onblur="
if(checkLength(cc_number.value) == true) {
alert('Sorry, that is not a valid number - Credit Card numbers must be nine digits!');
} else if (checkLetters(cc_number.value) == true) {
alert('Credit Card number must be numbers only, please re-enter the CC number using numbers only.');
}">
Any help or suggestions would be appreciated.
It looks like you're trying to validate credit card input. May I suggest a different approach?
function checkCardInput(input,errorId) {
var errorNoticeArea = document.getElementById(errorId);
errorNoticeArea.innerHTML = '';
if(!input.value) {
errorNoticeArea.innerHTML = 'This field cannot be left blank.';
return;
}
if(!input.value.match(/[0-9]/)) {
errorNoticeArea.innerHTML = 'You may only enter numbers in this field.';
input.value = '';
return;
}
if(input.value.length != 9) {
errorNoticeArea.innerHTML = 'Credit card numbers must be exactly 9 digits long.';
return;
}
}
See this jsFiddle for an example use.
You're passing cc_number.value as input, but then referencing input.value.match(), which works out to:
cc_number.value.value.match();
Just pass cc_number:
if (checkLetters(cc_number)) {
...
}

How to check for empty values on two fields then prompt user of error using javascript

I hope I can explain this right I have two input fields that require a price to be entered into them in order for donation to go through and submit.
The problem that I am having is that I would like the validation process check to see if one of the two fields has a value if so then proceed to submit. If both fields are empty then alert.
This is what I have in place now after adding some of the input i received earlier today:
function validate_required(field,alerttxt)
{
with (field)
{
if (value==null||value=="")
{
alert(alerttxt); return false;
}
else
{
return true;
}
}
}
function validate_form(thisform)
{
with (thisform)
{
if (validate_required(billing_name_first,"You must enter your first name to donate")==false)
{billing_name_first.focus();return false;}
else if (validate_required(billing_name_last,"You must enter your last name to donate")==false)
{billing_name_last.focus();return false;}
else if (validate_required(billing_address_street1,"You must enter your billing street address to donate")==false)
{billing_address_street1.focus();return false;}
else if (validate_required(billing_address_city,"You must enter your billing address city to donate")==false)
{billing_address_city.focus();return false;}
else if (validate_required(billing_address_state,"You must enter your billing address state to donate")==false)
{billing_address_state.focus();return false;}
else if (validate_required(billing_address_zip,"You must enter your billing address zip code to donate")==false)
{billing_address_zip.focus();return false;}
else if (validate_required(billing_address_country,"You must enter your billing address country to donate")==false)
{billing_address_country.focus();return false;}
else if (validate_required(donor_email,"You must enter your email address to donate")==false)
{donor_email.focus();return false;}
else if (validate_required(card_number,"You must enter your credit card number to donate")==false)
{card_number.focus();return false;}
else if (validate_required(card_cvv,"You must enter your credit card security code to donate")==false)
{card_cvv.focus();return false;}
else if (validate_required(input1,"Need to enter a donation amount to continue")==false && validate_required(input2, "Need to enter a donation amount to continue")==false)
{
input1.focus();
return false;
}
}
}
This works fine... other than the fact that I get a message that reads error undefined... which i click ok about 2 times then I get the correct alert and instead of allowing me to correct the problem in IE7 and IE8 the form just processes.
Thanks guys any help would do
Matt
If I am understanding correctly, you only want to do the alert if both of the inputs are empty. If that's the case here's a refactoring of your code that will handle that.
function validate_required(field)
{
with (field)
{
if (value==null||value=="")
{
return false;
}
else
{
return true;
}
}
}
function validate_form(thisform)
{
with (thisform)
{
if (validate_required(input1)==false && validate_required(input2)==false)
{
alert('Need a donation to continue');
input1.focus();
return false;
}
}
}
take the alert() out of your assessment function- you're trying to do too much at once. a function to determine if input is valid or not should do only that one thing.
determine the state of your inputs first and then do something like
var field1Pass = validate_required(input1);
var field2Pass = validate_required(input2);
if ( !(field1Pass && field2Pass) ) {
alert("Need a donation amount to continue");
// TODO: logic to determine which field to focus on
return false;
}
var msg = "Need a donation amount to continue";
function validate_required(value) {
if(isNaN(value) || value == null || value == "") {
return false;
}
return true;
}
function validate_form(thisform) {
var i1 = validate_required($(thisform.input1).val());
var i2 = validate_required($(thisform.input2).val());
if(!(i1 && i2)) {
alert(msg);
thisform.input2.focus();
return false;
}
}
Look at the jQuery validation plugin. With the plugin it would just be a matter setting up the rules properly. You could get fancier and replace the default messages if you want. Check out the examples.
<script type="text/javascript">
$(function() {
$('form').validate({
'input1': {
required: {
depends: function() { $('#input2').val() == '' }
}
}
});
});
</script>
This sets it up so that input1 is required if input2 is empty, which should be sufficient since if input1 has a value, you don't need input2 and if neither has a value, then it will show your message for input1.
<input type="text" name="input1" />
<input type="text" name="input2" />
Here's my take, with refocusing on the first field that failed:
<body>
<form action="#" onsubmit="return validate(this);">
<input type="text" name="val0" /><br />
<input type="text" name="val1" /><br />
<input type="submit" />
</form>
<script type="text/javascript">
function validate(form) {
var val0Elem = form.val0, val1Elem=form.val1, elementToFocus;
// check fields and save where it went wrong
if (!numeric(val0Elem.value)) {elementToFocus=val0Elem;}
else if (!numeric(val1Elem.value)) {elementToFocus=val1Elem;}
// if there is an element to focus now, some validation failed
if (elementToFocus) {
alert('Enter numbers in both fields, please.')
// using select() instead of focus to help user
// get rid of his crap entry :)
elementToFocus.select();
// ..and fail!
return false;
}
// Helper function, "if a string is numeric":
// 1: it is not 'falsy' (null, undefined or empty)
// 2: it is longer than 0 too (so that '0' can be accepted)
// 3: it passes check for numericality using the builtin function isNaN
function numeric(s) {return (s && s.length>0 && !isNaN(s));}
}
</script>
</body>

Is there a version of MM_validateForm that works with pre-populated form fields?

Is there a version of the standard DreamWeaver MM_validateForm JavaScript function that takes into consideration pre-populated titles-as-values of form fields? Such as
<input type="text" name="fname" value="Enter your first name" />
which is displayed in a lighter grey color or something. Since this value is already filled, the validation routine passes, which is not correct. How do I fix this?
I don't use DreamWeaver much, so I don't know where to look exactly.
You can use the empty arguments of the MM_validateForm() call.
Change the call to MM_validateForm('name','Enter your first name','R',...).
Change the function MM_validateForm() to
<script type="text/javascript">
// Version 4.0
function MM_validateForm() { //v4.0
var i,p,q,nm,test,num,min,max,errors='',args=MM_validateForm.arguments;
for (i=0; i<(args.length-2); i+=3) { test=args[i+2]; val=MM_findObj(args[i]);
if (val) { nm=val.name; val=val.value; if (val!="" && val!=args[i+1]) {
if (test.indexOf('isEmail')!=-1) { p=val.indexOf('#');
if (p<1 || p==(val.length-1)) errors+='- '+nm+' must contain an e-mail address.\n';
} else if (test!='R') {
if (isNaN(val)) errors+='- '+nm+' must contain a number.\n';
if (test.indexOf('inRange') != -1) { p=test.indexOf(':');
min=test.substring(8,p); max=test.substring(p+1);
if (val<min || max<val) errors+='- '+nm+' must contain a number between '+min+' and '+max+'.\n';
} } } else if (test.charAt(0) == 'R') errors += '- '+nm+' is required.\n'; }
} if (errors) alert('The following error(s) occurred:\n'+errors);
document.MM_returnValue = (errors == '');
}
</script>
In short. Change line
if (val) { nm=val.name; if ((val=val.value)!="") {
to
if (val) { nm=val.name; val=val.value; if (val!="" && val!=args[i+1]) {

Categories